我在触发器中使用动态 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;
......
第二个条件,我确信它不会产生任何结果,但发现它仍然是正确的,有什么解决方案可以使它起作用吗?
最佳答案
您可以改用get diagnostics
:
...
declare
rcount int;
begin
execute 'select * from some_table';
get diagnostics rcount = row_count;
if rcount = 0 then
...
Note in particular that EXECUTE changes the output of GET DIAGNOSTICS, but does not change FOUND.
关于postgresql - 执行动态 sql 未设置在 psql 中找到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32182107/