DBCC CHECKCONSTRAINTS (Transact-SQL)
Checks the integrity of a specified constraint or all constraints on a specified table in the current database.
DBCC CHECKCONSTRAINTS constructs and executes a query for all FOREIGN KEY constraints and CHECK constraints on a table.
For example, a foreign key query is of the following form:
SELECT <columns>
FROM <table_being_checked> LEFT JOIN <referenced_table>
ON <table_being_checked.fkey1> = <referenced_table.pkey1>
AND <table_being_checked.fkey2> = <referenced_table.pkey2>
WHERE <table_being_checked.fkey1> IS NOT NULL
AND <referenced_table.pkey1> IS NULL
AND <table_being_checked.fkey2> IS NOT NULL
AND <referenced_table.pkey2> IS NULL
The query data is stored in a temp table. After all requested tables or constraints have been checked, the result set is returned.
DBCC CHECKCONSTRAINTS checks the integrity of FOREIGN KEY and CHECK constraints but does not check the integrity of the on-disk data structures of a table. These data structure checks can be performed by using DBCC CHECKDB and DBCC CHECKTABLE.
DBCC CHECKCONSTRAINTS return a rowset with the following columns.
|
Column name |
Data type |
Description |
|---|---|---|
|
Table Name |
varchar |
Name of the table. |
|
Constraint Name |
varchar |
Name of the constraint that is violated. |
|
Where |
varchar |
Column value assignments that identify the row or rows violating the constraint. The value in this column can be used in a WHERE clause of a SELECT statement querying for rows that violate the constraint. |
A. Checking a table
The following example checks the constraint integrity of the table Table1 in the AdventureWorks database.
USE AdventureWorks2012; GO CREATE TABLE Table1 (Col1 int, Col2 char (30)); GO INSERT INTO Table1 VALUES (100, 'Hello'); GO ALTER TABLE Table1 WITH NOCHECK ADD CONSTRAINT chkTab1 CHECK (Col1 > 100); GO DBCC CHECKCONSTRAINTS(Table1); GO
B. Checking a specific constraint
The following example checks the integrity of the CK_ProductCostHistory_EndDate constraint.
USE AdventureWorks2012;
GO
DBCC CHECKCONSTRAINTS ("Production.CK_ProductCostHistory_EndDate");
GO
C. Checking all enabled and disabled constraints on all tables
The following example checks the integrity of all enabled and disabled constraints on all tables in the current database.
DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS; GO