Copy schema and create new schema with different name in the same data base

前端 未结 8 850
慢半拍i
慢半拍i 2020-12-14 18:33

I there a way to copy the existing schema and generate new schema with another name in the same database in postgres.

8条回答
  •  -上瘾入骨i
    2020-12-14 19:09

    In the case you are OK with only tables and columns (without constraints, keys etc.) this simple script could be helpful

    DO LANGUAGE plpgsql
    $body$
    DECLARE
       old_schema NAME = 'src_schema';
       new_schema NAME = 'dst_schema';
       tbl TEXT;
       sql TEXT;
    BEGIN
      EXECUTE format('CREATE SCHEMA IF NOT EXISTS %I', new_schema);
    
      FOR tbl IN
        SELECT table_name
        FROM information_schema.tables
        WHERE table_schema=old_schema
      LOOP
        sql := format(
                'CREATE TABLE IF NOT EXISTS %I.%I '
                'AS '
                'SELECT * FROM %I.%I'
                , new_schema, tbl, old_schema, tbl);
        raise notice 'Sql: %', sql;
    
        EXECUTE sql;
      END LOOP;
    END
    $body$;
    

提交回复
热议问题