Skip to content

Instantly share code, notes, and snippets.

@BrianRosamilia
Last active August 19, 2016 17:41
Show Gist options
  • Save BrianRosamilia/28e68bc5201a670a09dabc2526308d39 to your computer and use it in GitHub Desktop.
Save BrianRosamilia/28e68bc5201a670a09dabc2526308d39 to your computer and use it in GitHub Desktop.
Find Missing Foreign Keys in SQL Server
SELECT 'ALTER TABLE [' + sch.name + '].' + '[' + t.name + ']'
+ ' WITH CHECK ADD CONSTRAINT [FK_' + t.name + '_' + q.tableName + '] FOREIGN KEY([' + c.name + ']) REFERENCES ' +
+ '[' + q.schemaName + '].' + '[' + q.tableName + ']' + '([' + c.name + ']);' + CHAR(13)+CHAR(10) + 'GO'
as [script]
FROM sys.columns c
INNER JOIN sys.tables t
ON t.object_id = c.object_id
INNER JOIN sys.indexes i
ON i.object_id = t.object_id
LEFT JOIN sys.foreign_key_columns fkc_Parent
ON fkc_Parent.parent_column_id = c.column_id
AND fkc_Parent.parent_object_id = c.object_id
LEFT JOIN sys.foreign_key_columns fkc_Referenced
ON fkc_Referenced.Referenced_column_id = c.column_id
AND fkc_Referenced.Referenced_object_id = c.object_id
LEFT JOIN sys.index_columns ic
ON ic.index_id = i.index_id
AND ic.object_id = t.object_id
AND ic.column_id = c.column_id
inner join sys.schemas sch
on sch.schema_id = t.schema_id
inner join (
SELECT sch.[name] as schemaName, t.name as tableName, c2.name
FROM sys.columns c2
INNER JOIN sys.tables t
ON t.object_id = c2.object_id
INNER JOIN sys.indexes i
ON i.object_id = t.object_id
inner JOIN sys.index_columns ic
ON ic.index_id = i.index_id
AND ic.object_id = t.object_id
AND ic.column_id = c2.column_id
inner join sys.schemas sch
on sch.schema_id = t.schema_id
AND i.is_primary_key = 1) as q
on ( q.name = c.name )
WHERE fkc_Referenced.constraint_object_id IS NULL
AND fkc_Parent.constraint_column_id IS NULL
AND ic.index_column_id IS NULL
AND c.name LIKE '%id'
AND i.is_primary_key = 1
ORDER BY t.name, c.name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment