使用循环对PostgreSQL中的多个模式执行ad-hoc脚本

问题描述 投票:0回答:1

我在PostgreSQL中有一个如下所示的脚本:

SET SEARCH_PATH TO "foo";
{...500 lines of script...}

SET SEARCH_PATH TO "bar";
{...500 lines of script...}

SET SEARCH PATH TO "baz";
{...500 lines of script...}

...etc

500行脚本是每个模式的字符相同的字符,并且有几个模式。

有没有办法将这个减少到一个循环使用,比如和每个模式名称的字符串值数组?

postgresql loops
1个回答
0
投票

回答我自己的问题。在dba.stackexchange上阅读this topic后,看起来一般模式如下:

DO
$do$
DECLARE _schema text;
BEGIN
FOR _schema IN
  SELECT 'foo' UNION
  SELECT 'bar' UNION
  SELECT 'baz'
LOOP
EXECUTE 'SET LOCAL search_path = "' || _schema || '"';

// Add your SQL scripts here

END LOOP;
END
$do$
© www.soinside.com 2019 - 2024. All rights reserved.