Script to Generate All Foreign Keys in SQL Server

The script will generate your Foreign Keys definition.

SELECT 'ALTER TABLE '+OBJECT_NAME(F.PARENT_OBJECT_ID)+ ' ADD CONSTRAINT' + F.NAME + ' FOREIGN KEY'+'('+COL_NAME(FC.PARENT_OBJECT_ID,FC.PARENT_COLUMN_ID)+ ')'+'REFRENCES '+OBJECT_NAME (F.REFERENCED_OBJECT_ID)+'(' +COL_NAME(FC.REFERENCED_OBJECT_ID,FC.REFERENCED_COLUMN_ID)+')'
FROM SYS.FOREIGN_KEYS AS F
INNER JOIN SYS.FOREIGN_KEY_COLUMNS AS FC ON F.OBJECT_ID = FC.CONSTRAINT_OBJECT_ID


Leave a comment or a question in the comment area bellow if you fell like


Be a sport and

Search

Loading... Please wait

Subscribe to our Newsletter

Be a sport and

x