Created
June 11, 2020 22:55
-
-
Save lafleurh/4893e57775e9970d3dcff2c82b44c303 to your computer and use it in GitHub Desktop.
Gets all foreign keys for a table.
This file contains 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
-- Table for which to find foreign keys | |
DECLARE @TableName NVARCHAR(255) = 'MyTable' | |
-- Select foreign keys and delete statements to remove references. Also get a select. | |
-- Generated statements only work for tables with single column foreign keys. | |
SELECT | |
'DELETE FROM ' + pt.name + ' WHERE ' + pc.name + ' NOT IN (' + | |
'SELECT ' + rc.name + ' FROM ' + rt.name + ');' AS del, | |
'SELECT ' + pc.name + ' FROM ' + pt.name + ' WHERE ' + pc.name + ' NOT IN (' + | |
'SELECT ' + rc.name + ' FROM ' + rt.name + ');' AS sel, | |
f.name, pt.name, pc.name, '=', rt.name, rc.name, f.* | |
FROM sys.foreign_keys f INNER JOIN sys.tables pt | |
ON f.parent_object_id = pt.object_id | |
INNER JOIN sys.tables rt | |
ON f.referenced_object_id = rt.object_id | |
INNER JOIN sys.foreign_key_columns fc | |
ON f.object_id = fc.constraint_object_id | |
INNER JOIN sys.all_columns pc | |
ON fc.parent_object_id = pc.object_id AND fc.parent_column_id = pc.column_id | |
INNER JOIN sys.all_columns rc | |
ON fc.referenced_object_id = rc.object_id AND fc.referenced_column_id = rc.column_id | |
WHERE pt.name = @TableName OR rt.name = @TableName |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment