我有这个代码:
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
中的数据建立一个表。要写入的行。
我想要返回的是以下内容:
我的 returns table
做错了什么线以及如何实现我正在寻找的输出?另外,我是否必须创建一个函数才能使其工作?
最佳答案
示例如何将已删除的记录从表 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$
;
关于sql - 在 PostgreSQL IF/THEN 语句中使用 DELETE FROM...RETURNING,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69681984/