使用SQL Server 2012,我想将记录标记为无效。在此之前,我想检查是否引用了它的主键。
我尝试搜索"获取每个引用主键的表中的表名和列名列表"并“在每个引用主键的表中获取列名”但没有任何相关信息显示出来。这是一个棘手的问题(对我而言)。
答案 0 :(得分:0)
编辑:添加查询以列出所有外键,引用表的表以及引用它的那些表中的列。
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'
根据此帖子中的回复进行查询; How can I list all foreign keys referencing a given table in SQL Server?