Skip to main content

Posts

Showing posts with the label record

Quick Guide to User-Defined Types in Oracle PL/SQL

A Twitter follower recently asked for more information on user-defined types in the PL/SQL language, and I figured the best way to answer is to offer up this blog post. PL/SQL is a strongly-typed language . Before you can work with a variable or constant, it must be declared with a type (yes, PL/SQL also supports lots of implicit conversions from one type to another, but still, everything must be declared with a type). PL/SQL offers a wide array of pre-defined data types , both in the language natively (such as VARCHAR2, PLS_INTEGER, BOOLEAN, etc.) and in a variety of supplied packages (e.g., the NUMBER_TABLE collection type in the DBMS_SQL package). Data types in PL/SQL can be scalars, such as strings and numbers, or composite (consisting of one or more scalars), such as record types, collection types and object types. You can't really declare your own "user-defined" scalars, though you can define subtypes  from those scalars, which can be very helpful from the p...

Use records to improve readability and flexibility of your code

Suppose I've created a table to keep track of hominids : CREATE TABLE hominids ( hominid_name VARCHAR2 (100), home_territory VARCHAR2 (100), brain_size_cm INTEGER ) / I might then write code like this: DECLARE l_b_hominid_name VARCHAR2 (100) := 'Bonobo'; l_b_brain_size_cm INTEGER := 500; l_g_hominid_name VARCHAR2 (100) := 'Gorilla'; l_g_brain_size_cm INTEGER := 750; l_n_hominid_name VARCHAR2 (100) := 'Neanderthal'; l_n_brain_size_cm INTEGER := 1800; What do you think? I find the little voice of Relational Theory inside my head rebelling. "All that repetition! All that denormalization ! All that typing (or copy-pasting, which is even worse)!" Surely if I should avoid having redundant data in rows of my tables, I should avoid redundant code, too? Yes, I should.   I don't like to see long lists of declarations, especially when the names are very similar and follow a pattern.  A f...