简体   繁体   中英

Run same script on under different schema - postgres

I have a script called populate.sql which contains create tables.

CREATE TABLE "EXAMPLE" (
.................
..............
);
CREATE TABLE "BlaBla" (
..........
........
);
CREATE TABLE ...

This script creates more than 20 tables. I want to run this populate.sql on top of different schemas. Let's say I want to run this script on schema1 , schema2 and schema3 .

Then I can write;

CREATE SCHEMA IF NOT EXISTS "schema1";
SET SCHEMA 'schema1';

on populate.sql and create those tables on one schema.

how can I create those tables on all schema within one psql command?

As far as I feel I have to do FOR LOOP on psql and create schema first and create tables on top of that scheme.

Tables will get created in the currently set search_path (if not otherwise specifically set in the create statement).

You could use a loop. In that loop you have to set the searchpath to your schema.

DO 
$$
  DECLARE schemaname text;
BEGIN
    FOR i IN 1..3 LOOP

    schemaname := 'schema' || i::text;

    execute 'CREATE SCHEMA ' || schemaname;
    execute 'SET SCHEMA ' || schemaname;    
    execute 'SET search_path TO ' || schemaname;

    -- conent of populate.sql

  END LOOP;
END
$$;

You cannot call external scripts inside this do block as mentioned by a_horse_with_no_name in the comments. Therefore this answer is only relevant if you want to extend your populate.sql file and wrap this do block around it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM