Thursday, 17 August 2017

Query to Generate alter statement to disable and enable foreign key constraints in SQL Server


SELECT 
distinct
OBJECT_NAME(f.parent_object_id) Reference_TableName,
'Alter table '+OBJECT_NAME(f.parent_object_id)+' nocheck constraint '+ f.name ALter_Statement_Disable,
'Delete from '+OBJECT_NAME (f.referenced_object_id) Delete_Statment,
'Alter table '+OBJECT_NAME(f.parent_object_id)+' check constraint '+ f.name ALter_Statement_Enable
FROM 
   sys.foreign_keys AS f
INNER JOIN 
   sys.foreign_key_columns AS fc 
      ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN 
   sys.tables t 
      ON t.OBJECT_ID = fc.referenced_object_id
WHERE 
   OBJECT_NAME (f.referenced_object_id) = 'dashboard'

No comments:

Post a Comment