PL/pg函数块

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 $$;

注意:计数器的当前值为1。

请注意,该 DO语句不属于该块。它用于执行匿名块。PostgreSQL DO从9.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';

If you use the double dollar ($$) you can avoid quoting issues. You can also use a token between $$ like $function$ or $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;
   
END outer_block $$;
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
posted @ 2020-04-29 13:32  Barry东东和西西  阅读(451)  评论(0编辑  收藏  举报