如何检查外键是否存在?

时间:2013-05-23 14:38:34

标签: sql sql-server foreign-keys

我想在表中找到一个外键,但是有重命名/更改主键的更改。如何确定表中的外键和主键?

相关代码:

SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
         WHERE CONSTRAINT_NAME = 'FK_Name'

3 个答案:

答案 0 :(得分:9)

随意使用此脚本,它会返回一个包含以下值的列表:

FKName  ParentTable  ParentColumnName    ReferencedTable    ReferencedColumnName

脚本:

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'
    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

答案 1 :(得分:3)

此查询应该为您提供一个开始 - 它为您提供外键名称以及父表和引用表名称和列:

select
    OBJECT_NAME(constraint_object_id),
    OBJECT_NAME(fkc.parent_object_id),
    scp.name,
    OBJECT_NAME(fkc.referenced_object_id),
    scr.name,
    fkc.constraint_column_id
from
    sys.foreign_key_columns fkc
        inner join
    sys.columns scp
        on
            fkc.parent_object_id = scp.object_id and
            fkc.parent_column_id = scp.column_id
        inner join
    sys.columns scr
        on
            fkc.referenced_object_id = scr.object_id and
            fkc.referenced_column_id = scr.column_id

如果您只是处理单列外键,那么您将希望使用适当的WHERE子句从此结果集中找到一行。

如果您有多列外键,则需要考虑多行匹配并应用GROUP BY OBJECT_NAME(constraint_object_id)并使用HAVING COUNT(*) = 列数

答案 2 :(得分:0)

对于那些想通过information_schema:

进行的人
IF EXISTS(
    SELECT rc.*
    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS rc 

    LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU1 
        ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG  
        AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA 
        AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME 

    WHERE KCU1.TABLE_NAME = 'YOUR_TABLE_NAME' 
    AND rc.CONSTRAINT_NAME = 'YOUR_FK_NAME' 
    -- AND rc.CONSTRAINT_SCHEMA = 'dbo' -- Optional
)
     PRINT 'I exist'