域名 AXUM.RS 将于2025年10月到期。我们无意再对其进行续费,我们希望你能够接续这个域名,让更多 AXUM 开发者继续受益。
  • 方案1️⃣AXUM.RS 域名 = 3000
  • 方案2️⃣方案1️⃣ + 本站所有专题原始 Markdown 文档 = 5000
  • 方案3️⃣方案2️⃣ + 本站原始数据库 = 5500
如果你有意接续这份 AXUM 情怀,请与我们取得联系。
说明:
  1. 如果有人购买 AXUM.RS 域名(方案1️⃣),或者该域名到期,本站将启用新的免费域名继续提供服务。
  2. 如果有人购买了 AXUM.RS 域名,且同时购买了内容和/或数据库(方案2️⃣/方案3️⃣),本站将关闭。届时我们或许会以另一种方式与你再相遇。

变量

本章将学习 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_namelast_name:都是数据类型为 VARCHAR(50) 变量,它们的初始值分别是 JohnDoe
  • payment:是一个初始值为 20.5 ,数据类型为 numeric(11,2) 的变量

变量初始化时序

PostgreSQL 计算变量的初始值,并一直在主体内保持,除非重新赋值给它:

复制数据类型

%type 可以获取字段或其它变量的数据类型。通常应该使用 %type 来声明指向数据库某字段或另一个变量值的变量。语法如下:

-- 声明具有指定字段数据类型的变量
变量名 表名.字段名%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 select_list
into variable_name
from table_expression;
do $$
declare
   actor_count integer; 
begin
   -- 统计演员数量,并将结果赋值给actor_count变量
   select count(*)
   into actor_count
   from actor;

   -- 显示演员数量
   raise notice '共有 % 个演员', actor_count;
end; $$
要查看完整内容,请先登录