Ámbito de variables
Cuando se declara de forma explícita una variable nueva (o nombre), el ámbito de la variable es el bloque en el que se define.
<<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;MYDB.SCHEMA(USER)=> call vals();
NOTICE: inner val != outer val 7 5
NOTICE: outer val is 5 5
VALS
------
(1 row)
<<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;
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)
Como se muestra en la salida, la variable val del iterador de bucle tiene su propio ámbito. Tiene su propio valor y no afecta a las otras dos definiciones de val. Dentro del bucle, si necesita llamar a una variable específica definida fuera del bucle for, puede utilizar el formato totalmente calificado del nombre de variable (etiqueta.variable).