Created
December 5, 2018 16:25
-
-
Save wriglz/11e415bd0ed55b44a0a8e919c899fdc5 to your computer and use it in GitHub Desktop.
Rename columns across multiple tables in the same schema in Postgres
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Call function with the schema name | |
CREATE OR REPLACE FUNCTION rename_columns(_schema text) RETURNS VOID AS $func$ | |
DECLARE | |
rec RECORD; | |
table RECORD; | |
result RECORD; | |
sql TEXT := ''; | |
i INTEGER; | |
BEGIN | |
-- Use the information_schema to find out all of the table names in the input schema. | |
FOR rec IN | |
SELECT table_name | |
FROM information_schema.tables | |
WHERE table_schema = _schema | |
-- Loop through all of the tables from the above statement renaming the columns: | |
LOOP | |
EXECUTE format('ALTER TABLE %I.%I RENAME COLUMN original_column TO renamed_column', _schema, rec.table_name); | |
END LOOP; | |
END; | |
$func$ LANGUAGE PLPGSQL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment