Created
October 21, 2015 11:47
-
-
Save ststeiger/70041c0dd12a41b43e52 to your computer and use it in GitHub Desktop.
Adding a primary key to table in a fault-tolerant manner (PostgreSQL)
This file contains hidden or 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
| DO $$ | |
| DECLARE __mytext character varying(200); | |
| BEGIN | |
| __mytext := 'Test message'; | |
| --RAISE NOTICE __mytext; | |
| RAISE NOTICE '%', __mytext; | |
| RAISE NOTICE '% %', 'arg1', 'arg2'; | |
| IF 0 < | |
| ( | |
| SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS | |
| WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' | |
| AND LOWER(TABLE_SCHEMA) = LOWER('public') | |
| AND LOWER(TABLE_NAME) = LOWER('T_SYS_ApertureColorToHex') | |
| AND LOWER(CONSTRAINT_NAME) = LOWER('PK_T_SYS_ApertureColorToHex') | |
| ) THEN | |
| RAISE NOTICE 'Dropping primary-key PK_T_SYS_ApertureColorToHex'; | |
| ALTER TABLE T_SYS_ApertureColorToHex DROP CONSTRAINT PK_T_SYS_ApertureColorToHex; | |
| END IF; | |
| IF 0 = | |
| ( | |
| SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS | |
| WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' | |
| AND TABLE_SCHEMA = 'public' | |
| AND LOWER(TABLE_NAME) = LOWER('T_SYS_ApertureColorToHex') | |
| -- AND LOWER(CONSTRAINT_NAME) = LOWER('PK_T_SYS_ApertureColorToHex') | |
| ) THEN | |
| RAISE NOTICE 'Creating primary-key PK_T_SYS_ApertureColorToHex'; | |
| ALTER TABLE T_SYS_ApertureColorToHex ADD CONSTRAINT PK_T_SYS_ApertureColorToHex PRIMARY KEY (COL_Aperture); | |
| END IF; | |
| END$$; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment