postgresql - 执行动态 sql 未设置在 psql 中找到

标签 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;
......

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

最佳答案

您可以改用get diagnostics:

...
declare
    rcount int;
begin
    execute 'select * from some_table';
    get diagnostics rcount = row_count;
    if rcount = 0 then
        ...

根据 the documentation:

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/

相关文章:

ruby-on-rails - 命名空间模型 + postgresql 问题

postgresql - 在 Amazon ec2 linux 上更改 postgresql 9.3 数据库位置

postgresql - 无效交易终止

ruby-on-rails - rails 只加入那些所有成员都年满 18 岁的组

database - 防止 PostgreSQL 有时选择错误的查询计划

postgresql - plpgsql动态数学/比较运算符计算?

sql - 外键死锁如何删除记录?

sql - 使用 id 和树状表的后代连接两个表

sql - 作为 Postgres 中另一个函数的参数的函数

sql - 使用 Postgres 版本 9.3 使用多个 WITH tablename AS (...) 语句