Skip to content

Instantly share code, notes, and snippets.

Created October 27, 2020 02:15
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
SQL Sever - List table relationship
DECLARE @tableName VARCHAR(64);
SET @tableName = 'MY_TABLE_NAME';
SELECT AS parent_table
, AS parent_column
, 'is a foreign key of' AS direction
, AS referenced_table
, AS referenced_column
, *
sys.foreign_key_columns FKC
INNER JOIN sys.objects SO_P ON SO_P.object_id = FKC.parent_object_id
INNER JOIN sys.columns SC_P ON (SC_P.object_id = FKC.parent_object_id) AND (SC_P.column_id = FKC.parent_column_id)
INNER JOIN sys.objects SO_R ON SO_R.object_id = FKC.referenced_object_id
INNER JOIN sys.columns SC_R ON (SC_R.object_id = FKC.referenced_object_id) AND (SC_R.column_id = FKC.referenced_column_id)
(( = @tableName) AND (SO_P.type = 'U'))
((UPPER( = UPPER(@tableName)) AND (SO_R.type = 'U'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment