将列引用为外键的所有列

时间:2016-09-16 10:17:55

标签: sql-server reference foreign-keys primary-key

如何将其他表/模式中引用某个列A作为外键的所有列的列表?

1 个答案:

答案 0 :(得分:0)

这样的东西?

SELECT
    fk.Name,
    'Referenced table' = refTbl.Name,
    'Parent table' = parentTbl.Name,
    'Parent column' = c.name
FROM 
    -- FK constraint
    sys.foreign_keys fk
INNER JOIN 
    -- Referenced table (where the PK resides)
    sys.tables refTbl ON fk.referenced_object_id = refTbl.object_id
INNER JOIN 
    -- Parent table (which has the foreign key column)
    sys.tables parentTbl ON fk.parent_object_id = parentTbl .object_id
INNER JOIN 
    -- link to the columns involved in the FK contraint
    sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN 
    -- column in the parent table that's part of the FK constraint
    sys.columns c ON c.object_id = parentTbl.object_id AND c.column_id = fkc.parent_column_id
WHERE
    refTbl.name = 'YourTableNameHere'
ORDER BY
    fk.Name, parentTbl.name