Monday, November 2, 2009

Script to Enable/Disable All Foreign Keys

To generate SQL statements which will disable all foreign key constraints in a database, you can use this script

select 'ALTER TABLE [' + s.name + '].[' + t.name + '] NOCHECK CONSTRAINT [' + fk.name +'];'
as script
from sys.foreign_keys fk inner join sys.tables t on fk.parent_object_id = t.object_id
inner join sys.schemas s on t.schema_id = s.schema_id

To enable foreign key the NOCKECK keyword needs to be changed to CHECK

If data was inserted when tables foreign keys were disabled and would like to check integrity,
DBCC CHECKCONSTRAINTS('TABLE_NAME') [WITH ALL_CONSTRAINTS] can be used
the optional WITH ALL_CONSTRAINT is used to include all constraints even the ones that are disabled even the ones

Here is a capture script from sql profile to see all foreign keys and their columns

SELECT
SCHEMA_NAME(tbl.schema_id) AS [Table_Schema],
tbl.name AS [Table_Name],
cstr.name AS [ForeignKey_Name],
fk.constraint_column_id AS [ID],
cfk.name AS [Name],
crk.name AS [ReferencedColumn]
FROM
sys.tables AS tbl
INNER JOIN sys.foreign_keys AS cstr ON cstr.parent_object_id=tbl.object_id
INNER JOIN sys.foreign_key_columns AS fk ON fk.constraint_object_id=cstr.object_id
INNER JOIN sys.columns AS cfk ON fk.parent_column_id = cfk.column_id and fk.parent_object_id = cfk.object_id
INNER JOIN sys.columns AS crk ON fk.referenced_column_id = crk.column_id and fk.referenced_object_id = crk.object_id
ORDER BY
[Table_Schema] ASC,[Table_Name] ASC,[ForeignKey_Name] ASC,[ID] ASC

No comments:

Post a Comment