0

Using SQL Server 2012, I want to mark a record inactive. Before I do, I want to check if its primary key is referenced.

I tried searching on "get a list of the table name and column name in each table that references primary key" and “get column name in each table that references primary key” but nothing relevant showed up. This is a tricky question to search on (for me).

Ashwin Nirmul
  • 61
  • 1
  • 8

1 Answers1

0

EDIT: Adding a query to list all foreign keys, tables that reference to your table, and columns in those tables that reference to it.

SELECT  obj.name AS FK_NAME,
    sch.name AS [schema_name],
    tab1.name AS [table],
    col1.name AS [column],
    tab2.name AS [referenced_table],
    col2.name AS [referenced_column]
FROM sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
    ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
    ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
    ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
    ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.tables tab2
    ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
    ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id
WHERE tab2.name = 'TABLENAME'

Query based on a reply in this thread; How can I list all foreign keys referencing a given table in SQL Server?