Skip to content

Instantly share code, notes, and snippets.

@Shuusan
Created April 5, 2024 02:01
Show Gist options
  • Save Shuusan/23a968f234966b04044ca2d7714a7eb5 to your computer and use it in GitHub Desktop.
Save Shuusan/23a968f234966b04044ca2d7714a7eb5 to your computer and use it in GitHub Desktop.
SQL - Constraint Check
SELECT *
FROM INFORMATION_SCHEMA.CHECK_CONSTRAINTS
--WHERE CONSTRAINT_NAME = '';
SELECT
tbl.name AS TableName,
col.name AS ColumnName,
con.name AS ConstraintName,
con.type_desc AS ConstraintType
FROM
sys.objects con
INNER JOIN sys.tables tbl ON con.parent_object_id = tbl.object_id
LEFT JOIN sys.index_columns ic ON ic.object_id = con.parent_object_id AND ic.index_id = con.parent_object_id
LEFT JOIN sys.columns col ON col.object_id = tbl.object_id AND col.column_id = ic.column_id
WHERE
con.type IN ('PK', 'FK', 'UQ', 'C', 'D') -- P = Primary Key, FK = Foreign Key, UQ = Unique, C = Check, D = Default
ORDER BY
TableName,
ColumnName,
ConstraintType,
ConstraintName;
SELECT
OBJECT_SCHEMA_NAME(parent_object_id) AS SchemaName,
OBJECT_NAME(parent_object_id) AS TableName,
name AS ConstraintName,
definition
FROM
sys.check_constraints;
--if exist, uncomment line below
--ALTER TABLE <table_name> DROP CONSTRAINT <constraint_name>;
ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name> CHECK <constraint_formula>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment