Script To Copy Table Data From One Schema To Another Schema
Script To Copy Table Data From One Schema To Another Schema
Facebookgoogle_plusTwitterLinkedInPinterestRedd
itPocketShare
In this post, I am sharing one script to copy your Schema tables into another Schema of
PostgreSQL.
I found this script at wiki.postgresql.org and modified the coding standard for the best
use.
In our organization, I am creating a different schema for all the database developers,
and at every new schema, we require to migrate development origin schema’s table
data into a newly created schema.
I created different database users for each database developer, and they can only access
their assigned schema. I am doing this for security reason, and it is also very easy to
audit the changes and work progress of all the database developers.
Create a below function and execute to migrate your schema.
Create a function to copy old schema data to new schema:
1 CREATE OR REPLACE FUNCTION fn_CopySchemaData(source_schema text, dest_schema te
2 xt)
3 RETURNS void AS
4 $$
5
6 DECLARE
7 object text;
8 buffer text;
9 default_ text;
10 column_ text;
11 BEGIN
12
13 -- Create a new schema
14 EXECUTE 'CREATE SCHEMA ' || dest_schema;
15
16 FOR object IN
17 SELECT sequence_name::text
18 FROM information_schema.SEQUENCES
19 WHERE sequence_schema = source_schema
20 LOOP
21 EXECUTE 'CREATE SEQUENCE ' || dest_schema || '.' || object;
22 END LOOP;
23
24 FOR object IN
25 SELECT TABLE_NAME::text
26 FROM information_schema.TABLES
27 WHERE table_schema = source_schema
28 LOOP
29 buffer := dest_schema || '.' || object;
30 EXECUTE 'CREATE TABLE ' || buffer || ' (LIKE ' || source_schema || '.' || object || ' INC
31 LUDING CONSTRAINTS INCLUDING INDEXES INCLUDING DEFAULTS)';
32
33 FOR column_, default_ IN
34 SELECT column_name::text, REPLACE(column_default::text, source_schema,
35 dest_schema)
36 FROM information_schema.COLUMNS
37 WHERE table_schema = dest_schema
38 AND TABLE_NAME = object
39 AND column_default LIKE 'nextval(%' || source_schema || '%::regclass
40 )'
41 LOOP
42 EXECUTE 'ALTER TABLE ' || buffer || ' ALTER COLUMN ' || column_ || ' SET DEFA
43 ULT ' || default_;
44 END LOOP;
END LOOP;
END;
PostgreSQL: Move Table with Data from one Schema to another Schema
PostgreSQL: Shell script to copy table data from one server to another server
PostgreSQL: Find a list of active Temp tables with Size and User information
PostgreSQL: Script to find the count of objects for each Database Schema