本章将学习 PL/pgSQL 变量的相关知识。
简介
变量是指向内存位置的有意义的名称,它保存的值可以通过块进行修改。变量就是与特定的数据类型关联。
在使用变量之前,必须在 PL/pgSQL 块的声明部分进行声明。声明变量的语法如下:
变量名 数据类型 [:= 表达式];
变量名
:指定变量的名称。一个有意义的变量名是非常有必要的。数据类型
:将特定的数据类型与变量相关联[:= 表达式]
:可选的。可以给变量设置初始值。如果省略这部分,变量的初始值是NULL
以下示例说明了如何声明和初始化变量:
do $$
declare
counter integer := 1;
first_name varchar(50) := 'John';
last_name varchar(50) := 'Doe';
payment numeric(11,2) := 20.5;
begin
raise notice '% % % has been paid % USD',
counter,
first_name,
last_name,
payment;
end $$;
counter
变量:是一个初始值为1
的整数first_name
、last_name
:都是数据类型为VARCHAR(50)
变量,它们的初始值分别是John
和Doe
payment
:是一个初始值为20.5
,数据类型为numeric(11,2)
的变量
变量初始化时序
PostgreSQL 计算变量的初始值,并一直在主体内保持,除非重新赋值给它:
复制数据类型
-- 声明具有指定字段数据类型的变量
变量名 表名.字段名%type;
-- 声明具有另一个变量数据类型的变量
变量名 其它变量%type;
以示例数据库的 film
为例:
do $$
declare
film_title film.title%type;
featured_title film_title%type;
begin
-- 获取 ID 为 100 的电影的标题
select title
from film
into film_title
where film_id = 100;
-- 显示电影标题
raise notice 'ID为100的电影的标题是:%s', film_title;
end $$;
此示例声明了两个变量:
film_title
变量:与film
表中的title
字段具有相同的数据类型featured_title
变量:与film_title
变量具有相同的数据类型
使用类型复制功能,将获得以下优势:
- 首先,不需要知道所引用的字段或变量的数据类型
- 其实,如果引用的字段或变量的数据类型发生变量,无需手动更新变量的声明
块和子块中的变量
当你在子块中声明一个与外部块同名的变量时,外部块的变量将在子块中被隐藏。如果要访问外部块的变量,需要使用标签来限定其名称:
do $$
<<outer_block>>
declare
counter integer := 0;
begin
counter := counter + 1;
raise notice 'The current value of the counter is %', counter;
declare
counter integer := 0;
begin
counter := counter + 10;
raise notice 'Counter in the subblock is %', counter;
raise notice 'Counter in the outer block is %', outer_block.counter;
end;
raise notice 'Counter in the outer block is %', counter;
end outer_block $$;
/* 结果
NOTICE: The current value of the counter is 1
NOTICE: Counter in the subblock is 10
NOTICE: Counter in the outer block is 1
NOTICE: Counter in the outer block is 1
*/
使用SELECT INTO
将查询结果赋值给变量
通过 SELECT INTO
语句,可以将查询结果赋值给变量,语法如下:
示例:
do $$
declare
actor_count integer;
begin
-- 统计演员数量,并将结果赋值给actor_count变量
select count(*)
into actor_count
from actor;
-- 显示演员数量
raise notice '共有 % 个演员', actor_count;
end; $$