如何在 postgresql 脚本中存储变量?

How can I store a variable in a postgresql script?

我有以下脚本,我需要在其中找到给定的章节,更改状态,然后存储 activity 引用以稍后删除 activity(因为 [=11 中的 FK =] activity), 删除 chapter_published 引用然后使用 id_activity 最后删除父 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;

对于这种特定情况,您真的不需要变量。您可以通过修改公共 table 表达式的单个数据来实现此目的:

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);

如果您想获得某种 "variable" 定义,您可以在开头使用一个 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 中设置一个名为 myGUC,然后

set my.chapter_id = 15;

select current_setting('my.chapter_id'); --not typesafe