In SQL Server, we can query the sys.check_constraints
system catalog view to return a list of CHECK
constraints in the current database.
Example
SELECT
SCHEMA_NAME(schema_id) AS SchemaName,
OBJECT_NAME(parent_object_id) AS TableName,
COL_NAME(parent_object_id, parent_column_id) AS ColumnName,
name AS ConstraintName,
definition AS ConstraintDefinition
FROM sys.check_constraints;
Example result:
SchemaName TableName ColumnName ConstraintName ConstraintDefinition ---------- ------------ -------------------- --------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Sales Invoices ReturnedDeliveryData CK_Sales_Invoices_ReturnedDeliveryData_Must_Be_Valid_JSON ([ReturnedDeliveryData] IS NULL OR isjson([ReturnedDeliveryData])<>(0)) Sales SpecialDeals null CK_Sales_SpecialDeals_Exactly_One_NOT_NULL_Pricing_Option_Is_Required (((case when [DiscountAmount] IS NULL then (0) else (1) end+case when [DiscountPercentage] IS NULL then (0) else (1) end)+case when [UnitPrice] IS NULL then (0) else (1) end)=(1)) Sales SpecialDeals null CK_Sales_SpecialDeals_Unit_Price_Deal_Requires_Special_StockItem ([StockItemID] IS NOT NULL AND [UnitPrice] IS NOT NULL OR [UnitPrice] IS NULL)
I ran that against the WorldWideImporters
sample database.
The view returns the IDs of each constraint’s schema, parent table, and parent column. I used SCHEMA_NAME()
to get the schema name from its ID, OBJECT_NAME()
to get the table name from its ID, and COL_NAME()
to get the column name from its ID (the column ID/name only applies to column-level constraints).