3

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

相关代码:

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

3 回答 3

10

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

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
于 2013-05-23T14:46:51.270 回答
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(*) = 多个列

于 2013-05-23T14:46:02.543 回答
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' 
于 2015-09-08T13:04:00.613 回答