[英]How can I store a variable in a postgresql script?
I have the following script where I need to find a given chapter, change the state, then store the activity reference to remove the activity later (because of the FK in chapter_published
activity), delete the chapter_published
reference and then use the id_activity
to finally remove the parent activity. 我有以下脚本,我需要找到一个给定的章节,改变状态,然后将其存储在活动参考以后删除活动(因为FK在chapter_published
活动),删除chapter_published
参考,然后使用id_activity
最终删除父级活动。
How would I do that programatically using a postgresql script in a very simple way? 我如何以一种非常简单的方式使用postgresql脚本以编程方式进行此操作? And where is that documented? 并在哪里记录?
Below is an example of what I would be expecting to achieve: 以下是我期望实现的示例:
-- Manually find the chapter I want first
select * from ws_chapter;
-- store the chapter once so I don't have to repeat in each statement
@chapter_id = 15;
-- Update the state field
update chapter set cd_state = 'DRAFT' where id_chapter = @chapter_id;
-- Now get the id of the activity for later use
@activity_id = select id_activity from chapter_published where id_chapter = @chapter_id;
-- Make the delete
delete from chapter_published where id_chapter = @chapter_id;
delete from activity where id_activity = @activity_id;
You don't really need a variable for this specific case. 在这种情况下,您实际上并不需要变量。 You can achieve this with a single data modifying common table expression: 您可以通过修改公用表表达式的单个数据来实现:
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);
If you want to have some kind of "variable" definition you could do by using one CTE at the beginning: 如果您想使用某种“变量”定义,可以在开始时使用一个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 (
...
)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.