| The PostgreSQL 9.0 Reference Manual - Volume 2 - Programming Guide
by The PostgreSQL Global Development Group Paperback (6"x9"), 478 pages ISBN 9781906966065 RRP £14.95 ($19.95) Sales of this book support the PostgreSQL project! Get a printed copy>>> |
9.3 Declarations
All variables used in a block must be declared in the
declarations section of the block.
(The only exceptions are that the loop variable of a FOR loop
iterating over a range of integer values is automatically declared as an
integer variable, and likewise the loop variable of a FOR loop
iterating over a cursor's result is automatically declared as a
record variable.)
PL/pgSQL variables can have any SQL data type, such as
integer, varchar, and
char.
Here are some examples of variable declarations:
user_id integer; quantity numeric(5); url varchar; myrow tablename%ROWTYPE; myfield tablename.columnname%TYPE; arow RECORD;
The general syntax of a variable declaration is:
name [ CONSTANT ] type [ NOT NULL ] [ { DEFAULT | := }
expression ];
The DEFAULT clause, if given, specifies the initial value assigned
to the variable when the block is entered. If the DEFAULT clause
is not given then the variable is initialized to the
SQL null value.
The CONSTANT option prevents the variable from being
assigned to, so that its value will remain constant for the duration of
the block.
If NOT NULL
is specified, an assignment of a null value results in a run-time
error. All variables declared as NOT NULL
must have a nonnull default value specified.
A variable's default value is evaluated and assigned to the variable
each time the block is entered (not just once per function call).
So, for example, assigning now() to a variable of type
timestamp causes the variable to have the
time of the current function call, not the time when the function was
precompiled.
Examples:
quantity integer DEFAULT 32; url varchar := 'http://mysite.com'; user_id CONSTANT integer := 10;
| ISBN 9781906966065 | The PostgreSQL 9.0 Reference Manual - Volume 2 - Programming Guide | See the print edition |