Created
March 24, 2016 16:33
-
-
Save jimytc/e4742bf95e7e25bf10a0 to your computer and use it in GitHub Desktop.
Use PL/PGSQL to do UPSERT
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
CREATE OR REPLACE FUNCTION upsert(target_id INT, type_value TEXT) RETURNS VOID AS $$ | |
BEGIN | |
-- Try update first | |
UPDATE creation_metadata SET category = type_value | |
WHERE creation_id = target_id; | |
-- Return if UPDATE command runs successfully | |
IF FOUND THEN | |
RETURN; | |
END IF; | |
-- Since there's no record in creation_metada | |
-- We then add new row with INSERT command | |
INSERT INTO creation_metadata (creation_id, category) | |
VALUES (target_id, type_value); | |
END;co | |
$$ LANGUAGE 'plpgsql'; | |
SELECT upsert(id, type) FROM creations | |
WHERE type IS NOT NULL |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment