postgresql如何在foreach循环上运行解析分析

时间:2018-05-24 12:49:40

标签: postgresql query-performance sql-execution-plan explain

我正在尝试在postgresql中运行'explain analyze' foreach循环,但在postgres doc中找不到合适的示例。任何人都可以帮助我。

以下是示例

CREATE OR REPLACE FUNCTION xyz() RETURNS TRIGGER AS $xyz$
DECLARE
        idList integer[];

        aa integer;
        bb bigint;
        cc integer;
        dd smallint;

BEGIN
        IF NEW.severity = 7
        THEN     
             idList := array(select someid from sometable where someid like NEW.someid);

        END IF;
             FOREACH Id in ARRAY alarmIdList LOOP
                 select a, b, c, d
                        into aa, bb, cc , dd
                 from SomeActivetable where someid = Id;

                 insert into SomeTable2(ba, bb, bc, bd)
                     values(aa, bb, 6, dd);
             END LOOP;

        END IF;
        RETURN NEW;
END;
$xyz$ LANGUAGE plpgsql;

谢谢, 古拉夫

1 个答案:

答案 0 :(得分:0)

嗯,有一点奇怪的方法怎么做。请参阅下面的“概念证明” - 根据您的需求进行调整......

do $$
declare
    _idlist int[] := '{10,20,30}';
    i int;
    _q text;
    _t text;
begin
    foreach i in array _idlist loop
        _q := 'explain analyze select '||i;
        raise notice 'query: %', _q;
        for _t in execute _q loop
            raise notice '%', _t;
        end loop;
    end loop;
end; $$ language plpgsql;   

将在pgAdmin(或命令行上的STDERR)的“messages”窗口中输出,如下所示:

NOTICE:  query: explain analyze select 10
NOTICE:  Result  (cost=0.00..0.01 rows=1 width=4) (actual time=0.001..0.001 rows=1 loops=1)
NOTICE:  Planning time: 0.003 ms
NOTICE:  Execution time: 0.012 ms
NOTICE:  query: explain analyze select 20
NOTICE:  Result  (cost=0.00..0.01 rows=1 width=4) (actual time=0.001..0.001 rows=1 loops=1)
NOTICE:  Planning time: 0.004 ms
NOTICE:  Execution time: 0.004 ms
NOTICE:  query: explain analyze select 30
NOTICE:  Result  (cost=0.00..0.01 rows=1 width=4) (actual time=0.000..0.000 rows=1 loops=1)
NOTICE:  Planning time: 0.004 ms
NOTICE:  Execution time: 0.003 ms
DO

Query returned successfully in 127 msec.