我有以下脚本需要查找给定章节,更改状态,然后存储活动引用以便稍后删除活动(因为chapter_published
活动中的FK),删除{{1引用,然后使用chapter_published
最终删除父活动。
如何以非常简单的方式使用postgresql脚本以编程方式执行此操作?记录在哪里?
以下是我期望实现的一个例子:
id_activity
答案 0 :(得分:1)
对于这种特定情况,您实际上并不需要变量。您可以使用单个数据修改公用表表达式来实现此目的:
with updated as (
update chapter
set cd_state = 'DRAFT'
where id_chapter = 15
returning id_chapter
), delete_published as (
delete from chapter_published
where id_chapter in (select id_chapter from updated)
returning id_activity
)
delete from activity
where id_activity in (select id_activity from delete_published);
如果您想要某种“变量”定义,可以在开头使用一个CTE:
with variables (chapter_id) as (
values (15)
), updated as (
update chapter
set cd_state = 'DRAFT'
where id_chapter = (select chapter_id from variables)
), delete_published as (
...
)
...
答案 1 :(得分:0)
您可以使用内联PLPGSQL函数执行此操作:
do $$
declare
chapter_id int = 15;
begin
//do stuff;
end $$;
或者在名为postgresql.conf
的{{1}}中设置GUC,然后
my