如何找出什么FOREIGN KEY约束引用SQL Server中的表?


119

我正在尝试删除表,但收到以下消息:

消息3726,级别16,状态1,第3行
无法删除对象'dbo.UserProfile',因为它是由FOREIGN KEY约束引用的。
消息2714,级别16,状态6,第2
行在数据库中已经有一个名为“ UserProfile”的对象。

我环顾了SQL Server Management Studio,但找不到约束。如何找出外键约束?


2
我喜欢的sp_help“dbo.TableName”在这里看到更多的方式:stackoverflow.com/questions/483193/...
马克Boltuc

2
Worth noticing:通过@LittleSweetSeas答案将返回信息有关的外键用于给定的参考表,但是@ Gayathri-瓦玛的一个给定的答案细节父表。两者在不同的情况下都很有用,并且都赢得了自己的比赛:-)
伊扎尔·阿兹米(Izhar Aazmi)2014年

Answers:


224

这里是:

SELECT 
   OBJECT_NAME(f.parent_object_id) TableName,
   COL_NAME(fc.parent_object_id,fc.parent_column_id) ColName
FROM 
   sys.foreign_keys AS f
INNER JOIN 
   sys.foreign_key_columns AS fc 
      ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN 
   sys.tables t 
      ON t.OBJECT_ID = fc.referenced_object_id
WHERE 
   OBJECT_NAME (f.referenced_object_id) = 'YourTableName'

这样,您将获得引用表和列名。

根据注释建议进行编辑,以使用sys.tables代替通用sys.objects。谢谢,marc_s


您应该使用更具针对性的方法,sys.tables而不是sys.objects
marc_s 2013年

@marc_s:谢谢,但是你能举个例子吗?sys.tables中的AFAIK我没有FK引用
LittleSweetSeas

3
我的意思是:替换INNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_idINNER JOIN sys.tables t ON t.OBJECT_ID = fc.referenced_object_id
marc_s

@LittleSweetSeas我仍然运行了上面的查询,但仍然没有得到具有外键约束的表的object_name和列名
Smart003 2015年

您可以通过以下更多信息来增强选择:SELECT f.name ConstraintName,f.type_desc ConstraintType,OBJECT_NAME(f.parent_object_id)ConstrainedTable,COL_NAME(fc.parent_object_id,fc.parent_column_id)ConstrainedColumn,OBJECT_NAME(f.referencedTable_object) ,COL_NAME(fc.referenced_object_id,fc.referenced_column_id)ReferencedColumn
DocOc

73

另一种方法是检查结果

sp_help 'TableName'

(或仅突出显示加引号的TableName和pres ALT + F1)

随着时间的流逝,我只是决定完善自己的答案。以下是sp_help提供的结果的屏幕截图。A在此示例中使用了AdventureWorksDW2012 DB。那里有很多很好的信息,而我们正在寻找的最终是-以绿色突出显示:

在此处输入图片说明


3
+1这提供了很多有用的信息,并且在输出的底部显示了外键
Hux 2014年

1
这使我以最少的代码行获得了很多信息
Rennish Joseph

这是最酷的快捷方式!彻底击败Ctl-R刷新架构!
杨先生

刷新本地InteliSense缓存= Ctrl + Shift + R; Ctrl + R =显示/隐藏结果窗格(或者至少这些是我对SSMS2008和SSMS2014的默认设置)
Vladislav

44

试试这个

SELECT
  object_name(parent_object_id) ParentTableName,
  object_name(referenced_object_id) RefTableName,
  name 
FROM sys.foreign_keys
WHERE parent_object_id = object_id('Tablename')

1
简短而优雅,加上对我有用!唯一的问题是name返回的值是内部名称(方法),而不是父表中的实际列名称。有任何解决这个问题的方法吗?
哈曼·塞缪尔

我在这里看到的内容ParentTableName将始终与Tablenamewhere子句中的给定“ ”(如果包含)相同。这可能是有意的,并且在查询多个表时将更加有用。
伊扎尔·阿兹米(Izhar Aazmi)2014年

28

我发现此答案非常简单,并针对我所需的技巧进行了欺骗:https : //stackoverflow.com/a/12956348/652519

来自链接的摘要,请使用以下查询:

EXEC sp_fkeys 'TableName'

快速简单。我能够很快找到所有外键表,相应的列和15个表的外键名称。

如下@mdisibio所述,这是指向详细说明可以使用的不同参数的文档的链接:https : //docs.microsoft.com/zh-cn/sql/relational-databases/system-stored-procedures/sp- fkeys-transact-sql


1
还有五个要过滤的参数,最有用的是第二个可以指定非默认模式的参数,例如EXEC sp_fkeys 'Payroll', 'accounting'
mdisibio

8

我正在使用此脚本查找与外键有关的所有详细信息。我正在使用INFORMATION.SCHEMA。下面是一个SQL脚本:

SELECT 
    ccu.table_name AS SourceTable
    ,ccu.constraint_name AS SourceConstraint
    ,ccu.column_name AS SourceColumn
    ,kcu.table_name AS TargetTable
    ,kcu.column_name AS TargetColumn
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
    INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
        ON ccu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME 
    INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu 
        ON kcu.CONSTRAINT_NAME = rc.UNIQUE_CONSTRAINT_NAME  
ORDER BY ccu.table_name

2
我正在寻找一种方法来查看作为外键的列以及该列引用的相关表,这样可以很好地进行总结。谢谢!
Nate Kindrew

@LittleSweetSeas答案显示了这些
错误

7

如果要在对象浏览器窗口中通过SSMS进行操作,请右键单击要删除的对象,然后查看依赖项。


7

这是在所有数据库中查找外键关系的最佳方法。

exec sp_helpconstraint 'Table Name'

还有另一种方法

select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME='Table Name'
--and left(CONSTRAINT_NAME,2)='FK'(If you want single key)

此解决方案exec sp_helpconstraint 'Table Name'是唯一为我返回任何行的解决方案。但是,约束名称是胡言乱语的。PRIMARY KEY (clustered) PK__org_soft__3213E83FE6B07364
Tor 2015年

4
SELECT 
    obj.name      AS FK_NAME,
    sch.name      AS [schema_name],
    tab1.name     AS [table],
    col1.name     AS [column],
    tab2.name     AS [referenced_table],
    col2.name     AS [referenced_column]
FROM 
     sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
    ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
    ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
    ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
    ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.tables tab2
    ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
    ON col2.column_id = referenced_column_id 
        AND col2.object_id =  tab2.object_id;

1

-以下内容可能会为您提供更多所需的信息:

create Procedure spShowRelationShips 
( 
    @Table varchar(250) = null,
    @RelatedTable varchar(250) = null
)
as
begin
    if @Table is null and @RelatedTable is null
        select  object_name(k.constraint_object_id) ForeginKeyName, 
                object_name(k.Parent_Object_id) TableName, 
                object_name(k.referenced_object_id) RelatedTable, 
                c.Name RelatedColumnName,  
                object_name(rc.object_id) + '.' + rc.name RelatedKeyField
        from sys.foreign_key_columns k
        left join sys.columns c on object_name(c.object_id) = object_name(k.Parent_Object_id) and c.column_id = k.parent_column_id
        left join sys.columns rc on object_name(rc.object_id) = object_name(k.referenced_object_id) and rc.column_id = k.referenced_column_id
        order by 2,3

    if @Table is not null and @RelatedTable is null
        select  object_name(k.constraint_object_id) ForeginKeyName, 
                object_name(k.Parent_Object_id) TableName, 
                object_name(k.referenced_object_id) RelatedTable, 
                c.Name RelatedColumnName,  
                object_name(rc.object_id) + '.' + rc.name RelatedKeyField
        from sys.foreign_key_columns k
        left join sys.columns c on object_name(c.object_id) = object_name(k.Parent_Object_id) and c.column_id = k.parent_column_id
        left join sys.columns rc on object_name(rc.object_id) = object_name(k.referenced_object_id) and rc.column_id = k.referenced_column_id
        where object_name(k.Parent_Object_id) =@Table
        order by 2,3

    if @Table is null and @RelatedTable is not null
        select  object_name(k.constraint_object_id) ForeginKeyName, 
                object_name(k.Parent_Object_id) TableName, 
                object_name(k.referenced_object_id) RelatedTable, 
                c.Name RelatedColumnName,  
                object_name(rc.object_id) + '.' + rc.name RelatedKeyField
        from sys.foreign_key_columns k
        left join sys.columns c on object_name(c.object_id) = object_name(k.Parent_Object_id) and c.column_id = k.parent_column_id
        left join sys.columns rc on object_name(rc.object_id) = object_name(k.referenced_object_id) and rc.column_id = k.referenced_column_id
        where object_name(k.referenced_object_id) =@RelatedTable
        order by 2,3



end

1

您还可以Foreign Keys通过适应@LittleSweetSeas答案来返回有关的所有信息:

SELECT 
   OBJECT_NAME(f.parent_object_id) ConsTable,
   OBJECT_NAME (f.referenced_object_id) refTable,
   COL_NAME(fc.parent_object_id,fc.parent_column_id) ColName
FROM 
   sys.foreign_keys AS f
INNER JOIN 
   sys.foreign_key_columns AS fc 
      ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN 
   sys.tables t 
      ON t.OBJECT_ID = fc.referenced_object_id
order by
ConsTable

1

在SQL Server Management Studio中,您可以右键单击对象资源管理器中的表,然后选择“查看依赖项”。这将为您提供一个良好的起点。它显示了引用该表的表,视图和过程。


0

请尝试以下查询。

select object_name(sfc.constraint_object_id) AS constraint_name,
       OBJECT_Name(parent_object_id) AS table_name ,
       ac1.name as table_column_name,
       OBJECT_name(referenced_object_id) as reference_table_name,      
       ac2.name as reference_column_name
from  sys.foreign_key_columns sfc
join sys.all_columns ac1 on (ac1.object_id=sfc.parent_object_id and ac1.column_id=sfc.parent_column_id)
join sys.all_columns ac2 on (ac2.object_id=sfc.referenced_object_id and ac2.column_id=sfc.referenced_column_id) 
where sfc.parent_object_id=OBJECT_ID(<main table name>);

这将提供constraint_name,将要引用的column_names和将取决于约束的表。


0

您可以使用此查询来显示Foreign key常量:

SELECT
K_Table = FK.TABLE_NAME,
FK_Column = CU.COLUMN_NAME,
PK_Table = PK.TABLE_NAME,
PK_Column = PT.COLUMN_NAME,
Constraint_Name = C.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
SELECT i1.TABLE_NAME, i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON PT.TABLE_NAME = PK.TABLE_NAME
---- optional:
ORDER BY
1,2,3,4
WHERE PK.TABLE_NAME='YourTable'

取自http://blog.sqlauthority.com/2006/11/01/sql-server-query-to-display-foreign-key-relationships-and-name-of-the-constraint-for-each-table-数据库内/


0

获得最简单的方法Primary Key,并Foreign Key为表:

/*  Get primary key and foreign key for a table */
USE DatabaseName;

SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE CONSTRAINT_NAME LIKE 'PK%' AND
TABLE_NAME = 'TableName'

SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE CONSTRAINT_NAME LIKE 'FK%' AND
TABLE_NAME = 'TableName'

0

在对象资源管理器中,展开表,然后展开“键”:

在此处输入图片说明

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.