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语句可以履行匿名块。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有毛病或未斟酌完全的地方,望不吝赐教。
文章来源:丸子建站
文章标题:PostgreSQL数据库中匿名块的写法实例
https://www.wanzijz.com/view/63631.html