Disabling keys and constraints to improve the performance of load data is a common practice in large data warehouses and other environments with big tables.
This technique is relatively more natural and safer than dropping and recreating all the keys and constraints if you don’t forget to enable them after the work has been done.
Having untrusted or disabled FOREIGN KEY or CHECK constraints in your database may cause query performance problems with inadequate query plans and degrade data consistency and integrity.
How to check for untrusted foreign keys and constraints?
Use the script below to find untrusted foreign keys:
SELECT '[' + s.name + '].[' + o.name + '].[' + i.name + ']' AS KeyName
FROM sys.foreign_keys i
INNER JOIN sys.objects o ON i.parent_object_id = o.object_id
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE i.is_not_trusted = 1
AND i.is_not_for_replication = 0;Use the following script to get the list of untrusted constraints:
SELECT '[' + s.name + '].[' + o.name + '].[' + i.name + ']' AS KeyName
FROM sys.check_constraints i
INNER JOIN sys.objects o ON i.parent_object_id = o.object_id
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE i.is_not_trusted = 1
AND i.is_not_for_replication = 0
AND i.is_disabled = 0;How to restore trust for foreign keys and constraints?
Once you have that result set above, you can use the alter table statement to re-establish the trust for each result in the list.
Just replace “MyTableName” and “MyConstraintName” with your table name and foreign keys/constraints name in the code below.
ALTER TABLE MyTableName
WITH CHECK CHECK CONSTRAINT MyConstraintNameAlternatively, you can also run the script below that will generate the necessary T-SQL to recheck all the untrusted constraints:
SELECT N'ALTER TABLE ' + QUOTENAME(s.name) + N'.' + QUOTENAME(o.name) + N' WITH CHECK CHECK CONSTRAINT ' + QUOTENAME(c.name) + N';' AS ConstraintsToFix
FROM sys.check_constraints c
INNER JOIN sys.objects o ON c.parent_object_id = o.object_id
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE c.is_not_trusted = 1
AND c.is_not_for_replication = 0
AND c.is_disabled = 0The following script will generate the necessary T-SQL to recheck the untrusted foreign keys:
SELECT N'ALTER TABLE ' + QUOTENAME(s.name) + N'.' + QUOTENAME(o.name) + N' WITH CHECK CHECK CONSTRAINT ' + QUOTENAME(f.name) + N';' AS ForeignKeystoFix
FROM sys.foreign_keys f
INNER JOIN sys.objects o ON f.parent_object_id = o.object_id
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE f.is_not_trusted = 1
AND f.is_not_for_replication = 0More information:
Speak with a SQL Expert
In just 30 minutes, we will show you how we can eliminate your SQL Server headaches and provide operational peace of mind