PostgreSQL数据库中匿名块的写法实例

PostgreSQL数据库中匿名块的写法实例,第1张

PostgreSQL数据库匿名块的写法实例

看代码吧~

test=# DO $$DECLARE i record;
test$# BEGIN
test$# FOR i IN 1..10
test$# LOOP 
test$# execute 'select loop_insert(1)';
test$# END LOOP;
test$# END$$;
DO
test=# 

看匿名块的执行效果:

test=# select count(*) from lineitem;
 count 
-------
 7000
(1 row) 
test=# select count(*) from lineitem;
 count 
-------
 17000 ------------->>>>匿名块插入了10000条记录.
(1 row) 
test=# 

补充:PostgreSql 的PL/pgSQL 块结构 (在pgAdmin查询工具中如何执行语句块)

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中执行块,点击图示按钮:

注意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$ , procedureprocedureprocedure.

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语句可以执行匿名块。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/894989.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-14
下一篇 2022-05-14

发表评论

登录后才能评论

评论列表(0条)

保存