Technical Article

Generate Add Foreign Keys statements for the table

,

I was going through the painfull optimization of the database of creating better clustered indexes
(not the default ones on the primary key).

This operation was requiring removing all foreign keys to this table and then recreation them again.

I created this script to optimize this quite tidious task.

--Drop Constraint Statement
SELECT
'ALTER TABLE [dbo].[' + CCU.TABLE_NAME + '] DROP CONSTRAINT ' + RC.CONSTRAINT_NAME + CHAR(13) +' GO'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CCU
  ON RC.CONSTRAINT_NAME=CCU.CONSTRAINT_NAME
  AND RC.CONSTRAINT_SCHEMA=CCU.CONSTRAINT_SCHEMA
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU
  ON RC.UNIQUE_CONSTRAINT_NAME=KCU.CONSTRAINT_NAME
  AND RC.UNIQUE_CONSTRAINT_SCHEMA=KCU.CONSTRAINT_SCHEMA
WHERE KCU.TABLE_NAME='TourTableName'

--Add Constraint Statement
SELECT
'ALTER TABLE [dbo].[' + CCU.TABLE_NAME + '] ADD CONSTRAINT ' + RC.CONSTRAINT_NAME+ ' FOREIGN KEY  ( [' + CCU.COLUMN_NAME + ']) REFERENCES [dbo].[' + KCU.TABLE_NAME + '] ([' + KCU.COLUMN_NAME + ']) ' + CHAR(13) +' GO'
FROM 
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CCU
  ON RC.CONSTRAINT_NAME=CCU.CONSTRAINT_NAME
  AND RC.CONSTRAINT_SCHEMA=CCU.CONSTRAINT_SCHEMA
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU
  ON RC.UNIQUE_CONSTRAINT_NAME=KCU.CONSTRAINT_NAME
  AND RC.UNIQUE_CONSTRAINT_SCHEMA=KCU.CONSTRAINT_SCHEMA
WHERE KCU.TABLE_NAME='YourTableName'

Rate

1 (1)

You rated this post out of 5. Change rating

Share

Share

Rate

1 (1)

You rated this post out of 5. Change rating