Last active
March 8, 2017 20:55
-
-
Save tompazourek/7a34a1d2b832271bc8807ed2a95fbac5 to your computer and use it in GitHub Desktop.
Find foreign keys that don't have single-column indexes on them.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT | |
* | |
FROM | |
sys.foreign_keys fk | |
WHERE | |
EXISTS | |
( | |
SELECT | |
* | |
FROM | |
sys.foreign_key_columns fkc | |
WHERE | |
fkc.constraint_object_id = fk.object_id | |
AND NOT EXISTS | |
( | |
SELECT | |
* | |
FROM | |
sys.index_columns ic | |
WHERE | |
ic.object_id = fkc.parent_object_id | |
AND ic.column_id = fkc.parent_column_id | |
AND ic.index_column_id = fkc.constraint_column_id | |
AND | |
( | |
SELECT | |
COUNT(DISTINCT ic2.index_column_id) | |
FROM | |
sys.index_columns ic2 | |
WHERE | |
ic2.object_id = ic.object_id | |
AND ic2.index_id = ic.index_id | |
GROUP BY | |
ic2.object_id, | |
ic2.index_id | |
) = 1 | |
) | |
) | |
ORDER BY name |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT | |
tab.name AS [table_name], | |
col.name as [column_name], | |
'CREATE INDEX [IX_' + col.name + '] ON [' + tab.name + '] ([' + col.name + ']);' AS [script], | |
fk.*, | |
fkc.* | |
FROM | |
sys.foreign_keys fk | |
INNER JOIN | |
sys.foreign_key_columns fkc | |
ON fkc.constraint_object_id = fk.object_id | |
INNER JOIN | |
sys.tables tab | |
ON fkc.parent_object_id = tab.object_id | |
INNER JOIN | |
sys.columns col | |
ON | |
col.object_id = tab.object_id AND | |
col.column_id = fkc.parent_column_id | |
WHERE | |
EXISTS | |
( | |
SELECT | |
* | |
FROM | |
sys.foreign_key_columns fkc | |
WHERE | |
fkc.constraint_object_id = fk.object_id | |
AND NOT EXISTS | |
( | |
SELECT | |
* | |
FROM | |
sys.index_columns ic | |
WHERE | |
ic.object_id = fkc.parent_object_id | |
AND ic.column_id = fkc.parent_column_id | |
AND ic.index_column_id = fkc.constraint_column_id | |
AND | |
( | |
SELECT | |
COUNT(DISTINCT ic2.index_column_id) | |
FROM | |
sys.index_columns ic2 | |
WHERE | |
ic2.object_id = ic.object_id | |
AND ic2.index_id = ic.index_id | |
GROUP BY | |
ic2.object_id, | |
ic2.index_id | |
) = 1 | |
) | |
) | |
ORDER BY name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment