实现说明
一个文件里不止一条语句:SELECT / INSERT / CREATE,demo_totals、moved 都在涉及之列。
demo_totals 是由本文件里的语句当场建出来的会话级临时表——只活在当前会话,会话结束就自动清掉。
机制上由这些部分组成:用 COUNT 做聚合。
常见问题
这里用到哪些关系?
引用的是 demo_totals、moved。
核心语句
DO $$
BEGIN
RAISE NOTICE 'it''s fine to quote inside dollar quoting';
END $$;
代码示例
-- DO 块执行一次性匿名过程:不需要先 CREATE FUNCTION
DO $$
DECLARE
total integer := 0;
moved integer;
BEGIN
-- 整数 FOR 循环:边界含两端
FOR i IN 1..3 LOOP
total := total + i;
-- RAISE NOTICE 是过程块的进度输出,不中断执行
RAISE NOTICE 'step %, running total %', i, total;
END LOOP;
-- 倒序 FOR IN REVERSE:同一循环结构换个方向跑
FOR i IN REVERSE 3..1 LOOP
RAISE NOTICE 'countdown %', i;
END LOOP;
-- 过程块里也能碰表:建临时表、插入、聚合回读
CREATE TEMP TABLE demo_totals (step integer, value integer);
INSERT INTO demo_totals VALUES (1, total), (2, total * 2);
SELECT count(*) INTO moved FROM demo_totals;
RAISE NOTICE 'rows staged: %, final total: %', moved, total;
END $$;
-- NOTICE: step 1, running total 1
-- NOTICE: step 2, running total 3
-- NOTICE: step 3, running total 6
-- NOTICE: countdown 3
-- NOTICE: countdown 2
-- NOTICE: countdown 1
-- NOTICE: rows staged: 2, final total: 6
-- $$ 美元引用免转义:块内单引号无需翻倍
DO $$
BEGIN
RAISE NOTICE 'it''s fine to quote inside dollar quoting';
END $$;