/*
FIND ALL PRIMARY AND FOREIGN KEYS
*/
SELECT t.table_schema AS PrimarySchemaName
,t.TABLE_NAME AS PrimaryKeyTable
,tc.CONSTRAINT_NAME AS PrimaryKey
,COALESCE(tc2.constraint_schema, 'N/A') AS ForeignSchemaName
,COALESCE(rc1.CONSTRAINT_NAME, 'N/A') AS ForeignKey
,COALESCE(tc2.TABLE_NAME, 'N/A') AS ForeignKeyTable
,*
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
INNER JOIN INFORMATION_SCHEMA.TABLES t ON tc.TABLE_NAME = t.TABLE_NAME
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1 ON tc.CONSTRAINT_NAME = rc1.UNIQUE_CONSTRAINT_NAME
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME = rc1.CONSTRAINT_NAME
WHERE TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
ORDER BY tc.TABLE_NAME
,tc.CONSTRAINT_NAME
,rc1.CONSTRAINT_NAME
SELECT TC.CONSTRAINT_SCHEMA + '.' + TC.TABLE_NAME AS PRIMARYKEYTABLE
,TC.CONSTRAINT_NAME AS PRIMARYKEY
,COALESCE(RC1.CONSTRAINT_NAME, 'N/A') AS FOREIGNKEY
,CASE
WHEN TC2.TABLE_NAME IS NULL
THEN 'N/A'
ELSE TC.CONSTRAINT_SCHEMA + '.' + TC2.TABLE_NAME
END AS FOREIGNKEYTABLE
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC1 ON TC.CONSTRAINT_NAME = RC1.UNIQUE_CONSTRAINT_NAME
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC2 ON TC2.CONSTRAINT_NAME = RC1.CONSTRAINT_NAME
WHERE TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
ORDER BY TC.TABLE_NAME
,TC.CONSTRAINT_NAME
,RC1.CONSTRAINT_NAME
SELECT TC.CONSTRAINT_SCHEMA + '.' + TC.TABLE_NAME AS PRIMARYKEYTABLE
,TC.CONSTRAINT_NAME AS PRIMARYKEY
,CU.COLUMN_NAME AS [Primary Column Name]
,COALESCE(RC1.CONSTRAINT_NAME, 'N/A') AS FOREIGNKEY
,coalesce(CFU.Column_Name, 'N/A') AS [Foreign Column Name]
,CASE
WHEN TC2.TABLE_NAME IS NULL
THEN 'N/A'
ELSE TC.CONSTRAINT_SCHEMA + '.' + TC2.TABLE_NAME
END AS FOREIGNKEYTABLE
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CU ON TC.TABLE_NAME = CU.TABLE_NAME
AND TC.TABLE_SCHEMA = CU.TABLE_SCHEMA
AND Tc.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC1 ON TC.CONSTRAINT_NAME = RC1.UNIQUE_CONSTRAINT_NAME
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC2 ON TC2.CONSTRAINT_NAME = RC1.CONSTRAINT_NAME
LEFT JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CFU ON RC1.CONSTRAINT_NAME = CFU.CONSTRAINT_NAME
WHERE TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
ORDER BY TC.TABLE_NAME
,TC.CONSTRAINT_NAME
,RC1.CONSTRAINT_NAME
SELECT ccu.COLUMN_NAME, ccu.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS ccu
ON tc.CONSTRAINT_NAME = ccu.CONSTRAINT_NAME
WHERE tc.TABLE_CATALOG = 'Your_Catalog' -- replace with your catalog
AND tc.TABLE_SCHEMA = 'dbo' -- replace with your schema
AND tc.TABLE_NAME = 'Your_Table' -- replace with your table name
AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'