INFORMATION_SCHEMA外键

时间:2012-06-19 12:11:47

标签: sql tsql information-schema

我有这个代码,它允许我在tsql过程中识别标识列:

SELECT 
    c.column_name, (columnproperty(object_id(@table_name),c.column_name,'isIdentity')) pk
from information_schema.columns c
where c.table_name = @table_name

有人可以帮我修改这段代码,以便识别外键吗?

提前致谢

1 个答案:

答案 0 :(得分:2)

您可以使用此T-SQL语句获取引用特定表的所有外键:

;WITH ReferencingFK AS 
(
    SELECT 
        fk.Name AS 'FKName',
        OBJECT_NAME(fk.parent_object_id) 'ParentTable',
        cpa.name 'ParentColumnName',
        OBJECT_NAME(fk.referenced_object_id) 'ReferencedTable',
        cref.name 'ReferencedColumnName',
        fk.delete_referential_action,
        fk.update_referential_action
    FROM 
        sys.foreign_keys fk
    INNER JOIN 
        sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
    INNER JOIN 
        sys.columns cpa ON fkc.parent_object_id = cpa.object_id AND fkc.parent_column_id = cpa.column_id
    INNER JOIN 
        sys.columns cref ON fkc.referenced_object_id = cref.object_id AND fkc.referenced_column_id = cref.column_id
)
SELECT 
    FKName,
    ParentTable,
    ParentColumnName,
    ReferencedTable,
    ReferencedColumnName
FROM 
    ReferencingFK
WHERE
    ReferencedTable = 'YourTableNameHere'
ORDER BY 
    ParentTable, ReferencedTable, FKName

如果您想要所有外键,那么只需完全删除该WHERE子句。