Skip to content

Instantly share code, notes, and snippets.

@jerhon
Last active August 29, 2019 15:13
Show Gist options
  • Save jerhon/e30458ab802a910062a4d58414378f12 to your computer and use it in GitHub Desktop.
Save jerhon/e30458ab802a910062a4d58414378f12 to your computer and use it in GitHub Desktop.
Various SQL Server Queries that are helpful
-- Return referenced table name, and column for each foreign key constraint
DECLARE @TableID INT = OBJECT_ID('SCHEMA.TABLE')
select OBJECT_NAME(fkc.referenced_object_id) as referenced_table_name,
c.name as referenced_column,
fk.name as foreign_key_name,
OBJECT_NAME(fk.parent_object_id) as owning_table
from sys.foreign_keys fk
inner join sys.foreign_key_columns fkc on fk.object_id = fkc.constraint_object_id
inner join sys.columns c on fkc.referenced_column_id = c.column_id and fkc.parent_object_id = c.object_id
where fk.parent_object_id = @TableID
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment