Skip to main content
 首页 » 数据库

PostgreSql 的PL/pgSQL 块结构

2022年07月19日156虾米姐

PostgreSql 的PL/pgSQL 块结构

本文我们学习PL/pgSQL结构块,包括如何写结构块和执行结构块。

什么是结构块

PL/pgSQL是结构块语言,因此,PL/pgSQL函数或过程是通过结构块进行组织。完整结构块的语法如下:

[ <<label>> ] 
[ DECLARE 
    declarations ] 
BEGIN 
    statements; 
 ... 
END [ label ]; 

详细说明如下:

  • 块有两部分组成:声明部分和主体部分。声明部分是可选的,而主体部分是必须的。块在end关键字后面使用分号(;)表示结束。
  • 块可以有个可选的标签在开始和结尾处。如果你想在块主体中使用exit语句或限定块中声明的变量名称时,需要使用块标签。
  • 主体部分是编写代码的地方,每条语句需要使用分号结束。

PL/pgSQL 块结构示例

下面示例描述一个简单块结构,一般称为匿名块:

DO $$  
<<first_block>> 
DECLARE 
  counter integer := 0; 
BEGIN  
   counter := counter + 1; 
   RAISE NOTICE 'The current value of counter is %', counter; 
END first_block $$; 

运行结果:

NOTICE:  The current value of counter is 1 

从pgAdmin中执行块,点击图示按钮:
padmin
注意DO语句不属于块结构。它用于执行匿名块。PostgreSQL 在9.0版本中引入DO语句。
在声明部分定义变量counter并设置为0.

在主体部分,是counter值加1,通过RAISE NOTICE语句输出其值。

first_block 标签仅为了演示需要,本例中没有啥意义。

** 什么是双 ($$) 符号?**

($$) 符号 是单引号(’)的替代符号。开发PL/pgSQL 时,无论是函数或过程,必须把主体部分放在一个字符串中。因此必须对主体部分的单引号进行转义表示:

DO 
'<<first_block>> 
DECLARE 
  counter integer := 0; 
BEGIN  
   
    counter := counter + 1; 
    RAISE NOTICE ''The current value of counter is %'', counter; 
  
END first_block'; 

使用($$) 符号可以避免引号问题。也可以在$ 之 间 使 用 标 识 , 如 之间使用标识,如 使function$ , p r o c e d u r e procedure procedure.

PL/pgSQL 子结构块

PL/pgSQL可以一个块在另一个块的主体中。一个块嵌入在另一个块中称为子块,包含子块的块称为外部块。
子块
子块用于组织语句,这样大块能被分为更小和更多逻辑子块。子块的变量的名称可以与外部块变量名称同名,虽然这在实践中不建议。当在子块中声明一个与外部变量同名的变量,外部变量在子块中被隐藏。如果需要访问外部块的变量,可以使用块标签作为变量的限定符,如下面示例:

DO $$  
<<outer_block>> 
DECLARE 
  counter integer := 0; 
BEGIN  
   counter := counter + 1; 
   RAISE NOTICE 'The current value of counter is %', counter; 
  
   DECLARE  
       counter integer := 0; 
   BEGIN  
       counter := counter + 10; 
       RAISE NOTICE 'The current value of counter in the subblock is %', counter; 
       RAISE NOTICE 'The current value of counter in the outer block is %', outer_block.counter; 
   END; 
  
   RAISE NOTICE 'The current value of counter in the outer block is %', counter; 

执行结果如下:

NOTICE:  The current value of counter is 1 
NOTICE:  The current value of counter in the subblock is 10 
NOTICE:  The current value of counter in the outer block is 1 
NOTICE:  The current value of counter in the outer block is 1 
  • 首先,在外部块中声明变量counter。
  • 接着在子块中也声明了一个同名变量。
  • 在进入子块之前,变量的值为1。在子块中,我们给变量counter值加10,然后打印出来。注意,这个改变仅影响子块中counter变量。
  • 然后,我们通过标签限定符引用外部变量:outer_block.counter
  • 最后,我们打印外部块变量,其值保持不变。

总结

本文我们学习PL/pgSQL块结构,通过DO语句可以执行匿名块。


本文参考链接:https://blog.csdn.net/neweastsun/article/details/90311298
阅读延展