I've been trying to create a query that would return me the drop and create Foreing Key constraints on every table of a database
I was able to create the Script to drop constraint but I've not been able to create the script to recreate the constaint because
I cannot find the table and column names of the referenced table see bellow:
Here is an example demonstraiting the problem:
Created by EM:
ALTER TABLE Table_1 WITH NOCHECK ADD CONSTRAINT fk04 FOREIGN KEY ( column_1 ) REFERENCES owner.Table_2 ( column_2 ) NOT FOR REPLICATION
Created by the Scrip:
ALTER TABLE [owner].[Table_1] WITH NOCHECK ADD CONSTRAINT [owner].[fk04] FOREIGN KEY ( [column_1] ) REFERENCES [owner].[Table_1] ( [column_1] ) NOT FOR REPLICATION
Any help is greatly apreciated.
Thanks,
AL Almeida
Senior DBA
"May all those that come behind us, find us faithfull"
I was able to create the Script to drop constraint but I've not been able to create the script to recreate the constaint because
I cannot find the table and column names of the referenced table see bellow:
Code:
SELECT 'ALTER TABLE [' + t2.TABLE_SCHEMA+'.'+t2.Table_Name +
'] DROP CONSTRAINT ' + + t1.UNIQUE_CONSTRAINT_SCHEMA +
'.'+t1.Constraint_Name as 'Script to Drop Constraint'
, 'ALTER TABLE [' + t2.TABLE_SCHEMA +
'].['+ t2.TABLE_NAME +
'] WITH NOCHECK ADD CONSTRAINT [' + t2.CONSTRAINT_SCHEMA +
'].['+ t2.CONSTRAINT_NAME +
'] FOREIGN KEY ( '+ t2.COLUMN_NAME +
' ) REFERENCES ['+ t2.CONSTRAINT_SCHEMA +
'].['+ t2.TABLE_NAME +
'] ( ' + t2.COLUMN_NAME +
' ) NOT FOR REPLICATION' as 'Script to Create Constraint with NOT FOR REPLICATION'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS t1
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE t2
ON t1.CONSTRAINT_NAME = t2.CONSTRAINT_NAME
GO
Created by EM:
ALTER TABLE Table_1 WITH NOCHECK ADD CONSTRAINT fk04 FOREIGN KEY ( column_1 ) REFERENCES owner.Table_2 ( column_2 ) NOT FOR REPLICATION
Created by the Scrip:
ALTER TABLE [owner].[Table_1] WITH NOCHECK ADD CONSTRAINT [owner].[fk04] FOREIGN KEY ( [column_1] ) REFERENCES [owner].[Table_1] ( [column_1] ) NOT FOR REPLICATION
Any help is greatly apreciated.
Thanks,
AL Almeida
Senior DBA
"May all those that come behind us, find us faithfull"