Table Foreign Keys or Check Constraints Not Trusted

Generate a List of Untrusted Foreign Keys and Constraints as well as create the Alter Statement

***Caution Large Tables even on SQL Enterprise, You May Need an Outage Window

Checking of the existing data causes the entire table to be read/scanned and can take time and burn a lot of IO.  During this time it will require schema modification locks, so on large tables you may want to do this during maintenance windows if the table is large. As always, test this first on a restored backup of production in a development database server to get an idea of the time and resources.


--Generate list of affected foreign keys with this T-SQL script.  It must be run against the database in question:
SELECT '[' + s.name + '].[' + o.name + ']' AS Tablename, '[' + i.name + ']' AS Keyname,
'ALTER TABLE [' + s.name + '].[' + o.name + '] WITH CHECK CHECK CONSTRAINT [' + i.name + ']'+ ';' AS AlterStatement
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;
GO


Test





Comments

Popular posts from this blog

How to mass update all or some sql server agent job step commands

SQL Monitoring for Blocking and Locking Capture and Log to table with sp_WhoIsActive or sp_BlitzWho

SQL Server General Index Naming Convention