在 PostgreSQL IF / THEN 语句中使用 DELETE FROM...RETURNING
Using DELETE FROM...RETURNING in a PostgreSQL IF / THEN Statement
我有这个代码:
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”处或附近的语法错误
我本来是没有returns table
这一行的,但经过一番研究,我的理解是我需要为returning
这一行的数据建立一个table来写入进入.
我想要return的是:
msg
isSuccessful
test
1
我的 returns table
行有什么问题?如何获得我正在寻找的输出?另外,我是否必须创建一个函数才能使其工作?
示例如何将 table sample1
中删除的记录插入 table 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;
但是,如果你想获得 table 这种格式 (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$
;
我有这个代码:
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”处或附近的语法错误
我本来是没有returns table
这一行的,但经过一番研究,我的理解是我需要为returning
这一行的数据建立一个table来写入进入.
我想要return的是:
msg | isSuccessful |
---|---|
test | 1 |
我的 returns table
行有什么问题?如何获得我正在寻找的输出?另外,我是否必须创建一个函数才能使其工作?
示例如何将 table sample1
中删除的记录插入 table 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;
但是,如果你想获得 table 这种格式 (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$
;