[英]How can I store a variable in a postgresql script?
我有以下腳本,我需要找到一個給定的章節,改變狀態,然后將其存儲在活動參考以后刪除活動(因為FK在chapter_published
活動),刪除chapter_published
參考,然后使用id_activity
最終刪除父級活動。
我如何以一種非常簡單的方式使用postgresql腳本以編程方式進行此操作? 並在哪里記錄?
以下是我期望實現的示例:
-- 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;
在這種情況下,您實際上並不需要變量。 您可以通過修改公用表表達式的單個數據來實現:
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 (
...
)
...
您可以使用內聯PLPGSQL函數執行此操作:
do $$
declare
chapter_id int = 15;
begin
//do stuff;
end $$;
或者在postgresql.conf
設置一個名為my
的GUC ,然后
set my.chapter_id = 15;
select current_setting('my.chapter_id'); --not typesafe
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.