[PostgreSQL: create constraint if not exists] not sure of sql compatibility with other engines #postgres #constraint #sql
// vim: syntax=sql | |
CREATE OR REPLACE FUNCTION create_constraint_if_not_exists (t_name text, c_name text, constraint_sql text) | |
RETURNS void | |
AS | |
$BODY$ | |
BEGIN | |
-- Look for our constraint | |
IF NOT EXISTS (SELECT constraint_name | |
FROM information_schema.constraint_column_usage | |
WHERE constraint_name = c_name) THEN | |
EXECUTE 'ALTER TABLE ' || t_name || ' ADD CONSTRAINT ' || c_name || ' ' || constraint_sql; | |
END IF; | |
END; | |
$BODY$ | |
LANGUAGE plpgsql VOLATILE; | |
SELECT create_constraint_if_not_exists('foo', 'bar', 'CHECK (foobies < 100);'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Yes, It works in PostgreSQL