【问题标题】:Postgres stored proc delete statement not getting executedPostgres 存储过程删除语句未执行
【发布时间】:2018-08-26 13:15:55
【问题描述】:

我有一个如下所示的存储过程:

create function search_contacts
(_name text, _phone text, _email text, _address text, _threshold real)
  returns setof contact 
as $func$ 
declare
  _id uuid := uuid_generate_v4();
begin
  insert into _contact_index_tmp
    select...;
  insert into _contact_index_tmp
    select...;

  return query select c.* from _contact_index_tmp tmp left join 
  contact c
    on tmp.guid = c.contact_guid and tmp.query_id = _id;

  delete from _contact_index_tmp tmp 
  where tmp.query_id = _id;
  return;
end
$func$
language plpgsql;

我得到了我想要的结果(来自 return 查询语句),但最终的 delete 语句没有被执行,我用它来清理我的临时表。如何确保执行此操作?

【问题讨论】:

    标签: sql postgresql plpgsql sql-delete sql-function


    【解决方案1】:

    当您在函数中“返回”某些内容时,它会结束该函数,因此不会执行剩余的代码。 您需要将要返回的数据保存在临时变量中,删除数据,然后返回。

    【讨论】:

    • 如何将其保存在变量中并再次访问?我猜想使用数组/ unnest ...但我无法让某些东西正常工作
    • 来自documentationRETURN NEXT 和 RETURN QUERY 实际上并不从函数返回——它们只是将零或多行附加到函数的结果集
    【解决方案2】:

    你可以使用:

    return query 
    
    WITH cte AS (
       delete from _contact_index_tmp tmp      -- clear first
       where tmp.query_id = _id
       returning *                             -- return deleted data
    )
    select c.* 
    from cte tmp 
    left join contact c
      on tmp.guid = c.contact_guid;
    

    【讨论】:

    • return query 没有退出函数,下面的代码是可以访问的。
    • @klin...这就是我的想法...但是为什么删除语句没有被执行?
    • 事实上它已经执行了,但没有按预期工作。我不知道为什么。尝试在SqlFiddle 中复制此内容并给我们链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多