Re: Referencing uninitialized variables in plpgsql

From: John DeSoi <desoi(at)pgedit(dot)com>
To: "Karl O(dot) Pinc" <kop(at)meme(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Referencing uninitialized variables in plpgsql
Date: 2005-02-06 04:57:45
Message-ID: A40B4BC0-77FB-11D9-B584-000A95B03262@pgedit.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


On Feb 5, 2005, at 11:20 PM, Karl O. Pinc wrote:

> Is this example telling me I get NULL for unitialized references?
> I don't believe I should count on this behavior unless it's
> documented, should I?
>
> => create or replace function foo() returns int language plpgsql
> as 'declare a int; b int; begin a := b; return a; end; ';
> CREATE FUNCTION
> => select foo();

Yes, exactly. If you don't assign a value to a declared pspgsql
variable, it is NULL. Operations on NULL variables are no different
than operations on NULL values in the database. If you are concerned
about this, then always assign a value when you declare it.

Also, you can specify NOT NULL in your declaration to ensure a runtime
error is generated if the variable is null. See:

http://www.postgresql.org/docs/8.0/interactive/plpgsql-declarations.html

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 remains 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.

John DeSoi, Ph.D.
http://pgedit.com/
Power Tools for PostgreSQL

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Steve Atkins 2005-02-06 05:10:46 Re: security
Previous Message Karl O. Pinc 2005-02-06 04:30:49 Re: security