我有一个查询,它会返回一个列的名称
SELECT name
FROM sys.columns
WHERE object_id = OBJECT_ID('tblu_utenti_00') AND name LIKE '%ling%'
对于该列,我想知道它是否有FK以及FK指向哪个表。
答案 0 :(得分:1)
您可以查询目录视图以获取该信息 - 这是“通用”查询,它显示所有已定义的外键关系以及它们引用的表/列:
SELECT
ForeignKeyName = fk.name,
ParentTableName = parent.name,
ParentColumnName = parcol.name,
ReferencedTableName = referenced.Name,
ReferencedColumnName = refcol.name
FROM
sys.foreign_keys fk
INNER JOIN
sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id
INNER JOIN
sys.tables parent ON parent.object_id = fk.parent_object_id
INNER JOIN
sys.tables referenced ON referenced.object_id = fk.referenced_object_id
INNER JOIN
sys.columns parcol ON fkc.parent_object_id = parcol.object_id AND fkc.parent_column_id = parcol.column_id
INNER JOIN
sys.columns refcol ON fkc.referenced_object_id = refcol.object_id AND fkc.referenced_column_id = refcol.column_id
现在可以将此连接到sys.columns
查询,并检查该列是否用作任何外键约束中的“父列”或“引用列”。
.....
WHERE
(parent.Name = 'tblu_utenti_00' AND parcol.Name LIKE '%ling%')
OR
(referenced.Name = 'tblu_utenti_00' AND refcol.Name LIKE '%ling%')