psql 中未设置动态 sql 的执行

Tah*_*lal 4 postgresql plpgsql postgresql-9.3

我在触发器中使用动态 sql 执行 sql,因为触发器将跨多个表运行。sql将从表中选择并检查是否有结果,如果没有结果插入表中则不执行任何操作。它与第一个 psql select 一起工作,但找到的变量是 true,即使它是空的

 create function test() returns trigger $Body$
 execute 'select * from ' || quote_ident(TG_TABLE_NAME) || '_table1 where condition';

 if not found then
 insert into x values(anything);
 end if;

execute 'select * from ' || quote_indent(TG_TABLE_NAME) || '_table2 where condition';

if not found then
insert into y values (values);
end if;
......
Run Code Online (Sandbox Code Playgroud)

第二个条件我确信它不会产生任何结果,但发现仍然是正确的任何解决方案可以使其工作?

kli*_*lin 5

您可以使用get diagnostics

...
declare
    rcount int;
begin
    execute 'select * from some_table';
    get diagnostics rcount = row_count;
    if rcount = 0 then
        ...
Run Code Online (Sandbox Code Playgroud)

根据文档:

请特别注意 EXECUTE 会更改 GET DIAGNOSTICS 的输出,但不会更改 FOUND。