执行动态 sql 未设置在 psql 中找到
execute of dynamic sql does not set found in psql
我在触发器中使用动态 sql 执行 sql,因为触发器将 运行 跨越多个 table。 sql 将从 table 中 select 并检查是否有结果,如果没有结果插入 table,则不执行任何操作。它与第一个 psql select 一起工作,但找到的变量为真,即使它是空的
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.
我在触发器中使用动态 sql 执行 sql,因为触发器将 运行 跨越多个 table。 sql 将从 table 中 select 并检查是否有结果,如果没有结果插入 table,则不执行任何操作。它与第一个 psql select 一起工作,但找到的变量为真,即使它是空的
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.