Scope of variables
When you explicitly declare a new variable (or name), the scope of the variable is the block in which it is defined.
For example, the following sample defines a variable named val
in the DECLARE section of the <<outer>> block, and then defines
another val variable in the DECLARE section of the <<inner>>
block. Although the variables have the same name, these variables
are two different variables:
<<outer>>
DECLARE
val int4;
BEGIN
val := 5;
<<inner>>
DECLARE
val int4;
BEGIN
val := 7;
RAISE NOTICE 'inner val != outer val % %', val, outer.val;
END;
RAISE NOTICE 'outer val is 5 %', val;
END;
In this example, the block labels inner and outer can
be used to identify a specific val variable by using its fully qualified
variable name. If you create this procedure as a stored procedure
and run it, you would see output similar to the following:
MYDB.SCHEMA(USER)=> call vals();
NOTICE: inner val != outer val 7 5
NOTICE: outer val is 5 5
VALS
------
(1 row)
When you declare variables for loop iterators, the iterator variables
have their own unique scope. For example, you can use a variable named
val as a loop iterator. By using the same sample procedure, this would
give you three unique val variables in your procedure:
<<outer>>
DECLARE
val int4;
BEGIN
val := 5;
<<inner>>
DECLARE
val int4;
BEGIN
val := 7;
RAISE NOTICE 'inner val != outer val % %', val, outer.val;
FOR val IN 1 .. 10 LOOP
--Note that this is a NEW val variable for the loop.
RAISE NOTICE 'The value of val is %', val;
END LOOP;
RAISE NOTICE 'inner val is still 7. Value %', inner.val;
END;
RAISE NOTICE 'outer val is still 5. Value %', val;
END;
The following is sample output for this stored procedure:
MYDB.SCHEMA(USER)=> call vals();
NOTICE: inner val != outer val 7 5
NOTICE: The value of val is 1
NOTICE: The value of val is 2
NOTICE: The value of val is 3
NOTICE: The value of val is 4
NOTICE: The value of val is 5
NOTICE: The value of val is 6
NOTICE: The value of val is 7
NOTICE: The value of val is 8
NOTICE: The value of val is 9
NOTICE: The value of val is 10
NOTICE: inner val is still 7. Value 7
NOTICE: inner val is still 5. Value 5
VALS
------
(1 row)
As shown in the output, the val variable of the loop iterator has its own scope. It has its own value and does not affect the other two val definitions. Within the loop, if you need to call a specific variable that is defined outside the for loop, you can use the fully qualified form of the variable name (label.variable).