Advertisement
Guest User

Untitled

a guest
Jul 24th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.77 KB | None | 0 0
  1. ALTER TABLE t RENAME COLUMN IF EXISTS c1 TO c2
  2.  
  3. CREATE OR REPLACE FUNCTION column_exists(ptable TEXT, pcolumn TEXT)
  4. RETURNS BOOLEAN AS $BODY$
  5. DECLARE result bool;
  6. BEGIN
  7. -- Does the requested column exist?
  8. SELECT COUNT(*) INTO result
  9. FROM information_schema.columns
  10. WHERE
  11. table_name = ptable and
  12. column_name = pcolumn;
  13. RETURN result;
  14. END$BODY$
  15. LANGUAGE plpgsql VOLATILE;
  16.  
  17. CREATE OR REPLACE FUNCTION rename_column_if_exists(ptable TEXT, pcolumn TEXT, new_name TEXT)
  18. RETURNS VOID AS $BODY$
  19. BEGIN
  20. -- Rename the column if it exists.
  21. IF column_exists(ptable, pcolumn) THEN
  22. EXECUTE FORMAT('ALTER TABLE %I RENAME COLUMN %I TO %I;',
  23. ptable, pcolumn, new_name);
  24. END IF;
  25. END$BODY$
  26. LANGUAGE plpgsql VOLATILE;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement