Do Block Loops With Notice

Run anonymous procedural code inline with a DO block, using an integer FOR loop and RAISE NOTICE to emit progress lines from a psql session.

SqlCli Tooling

Code

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

What the code does

Several statements share this file — SELECT / INSERT / CREATE, with demo_totals and moved among the objects involved.

demo_totals is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.

Mechanically, the statements are built from: COUNT aggregation.

Using it

The file is self-contained: it creates the session-local tables it uses (demo_totals), so run it as a whole against a scratch database.

Key statements

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;

Interactive Tools for This Topic

FAQ

What are the relations in play here?
The references are `demo_totals`, `moved`.