How to move a table from one schema to another schema

posted Apr 28, 2017, 12:07 PM by Sachchida Ojha
CREATE OR REPLACE FUNCTION move_relation(VARCHAR, VARCHAR, VARCHAR)
RETURNS BOOL
AS '
-- $1 is the table name
-- $2 is the source schema
-- $3 is the destination schema
--
        UPDATE pg_catalog.pg_class
        SET relnamespace = (SELECT oid FROM pg_catalog.pg_namespace
                                WHERE nspname = $3)
        WHERE relnamespace = (SELECT oid FROM pg_catalog.pg_namespace
                                WHERE nspname = $2)
                AND relname = $1;
                                   
UPDATE pg_catalog.pg_type
        SET typnamespace = (SELECT oid FROM pg_catalog.pg_namespace
                                WHERE nspname = $3)
        WHERE typnamespace = (SELECT oid FROM pg_catalog.pg_namespace
                                WHERE nspname = $2)
                AND typname = $1;
                                                                                
        SELECT TRUE;
' LANGUAGE SQL;
Comments