【问题标题】:Using DELETE FROM...RETURNING in a PostgreSQL IF / THEN Statement在 PostgreSQL IF / THEN 语句中使用 DELETE FROM...RETURNING
【发布时间】:2021-12-09 09:35:26
【问题描述】:

我有这个代码:

DO $$
returns table (msg varchar(500), isSuccessful BIT) as $BODY$
declare
newID integer := null;
id integer := 100;
BEGIN
IF newID is NULL 
then delete from table1 t1 where t1.id = id;
delete from table2 t2 where t2.id = id
returning 'test' as msg, 1 as isSuccessful;
else insert into table1(id, name)
values(id, 'testname');
END IF;
END $$; 

当我运行它时,我收到了这个错误:

错误:“返回”处或附近的语法错误

我原本没有returns table这一行,但经过一番研究,我的理解是我需要为returning行中的数据建立一个表格来写入。

我要返回的内容如下:

msg isSuccessful
test 1

我的returns table 行有什么问题,如何实现我正在寻找的输出?另外,我是否必须创建一个函数才能使其工作?

【问题讨论】:

  • 您的函数期望一个数组作为结果。如果 newID 是 not NULL 会发生什么。你没有返回任何东西!
  • @Hamza Ok 更新了我的代码以插入到 ELSE 的 table1 中。我的 RETURNS TABLE 行仍然出现同样的错误。
  • 你不能通过DO(匿名)函数来return。见DO
  • @AdrianKlaver 我对函数的理解有限,但我理解你的评论。有没有办法在不定义函数的情况下实现我想要的输出?
  • 取决于你想用信息做什么。如果您只想发消息RAISE NOTICE 'msg: %, isSuccessful: %', msg, isSuccessful;。见这里Raising messages/errors。否则,您将不得不将其写到表格中。仅供参考,Postgres 有boolean,所以我会使用它而不是BIT。我会在这里花一些时间plpgsql

标签: sql postgresql function if-statement sql-delete


【解决方案1】:

示例如何将表 sample1 中已删除的记录插入表 sample2

with deleted_rows as (
    delete from test.sample1 where id = 123712
    returning id, first_name 
)
insert into test.sample2 (id, first_name) 
SELECT id, first_name from deleted_rows;

但是,如果你想获得这种格式的表格(msg,isSuccessful),那么:

CREATE OR REPLACE FUNCTION test.delete_data(p_id integer)
RETURNS table (msg text, isSuccessful boolean)
LANGUAGE plpgsql
AS $function$
declare 
    deleted_id integer; 
begin

    delete from test.sample1 where id = p_id
    returning id into deleted_id;
    -- if this query does not delete any record, so variable "deleted_id" will be null

    if (deleted_id is not null) then 
        return query 
        select 'Success Deleted', true;
    else 
        return query 
        select 'No records deleted', false;
    end if;

end;
$function$
;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-28
    • 2022-06-10
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多