SQL脚本查找特定表的外键?

时间:2011-10-21 17:43:14

标签: sql sql-server-2008 foreign-keys constraints

是否有一个查询可以获取针对特定表列的外键?例如,假设我有这三个表:

__________
|Table A |
----------
|Id      |
----------

___________
|Table B  |
-----------
|Id       |
|TableAId | (Foreign Key to TableA.Id)
-----------

___________
|Table C  |
-----------
|Id       |
|TableAId | (Foreign Key to TableA.Id)
-----------

我需要查询“Select *外键指向TableA.Id”,返回“表C:TableAId”,“表B:TableAId”。我正在浏览一些INFORMATION_SCHEMA系统视图,看起来我可以很容易地看到外键分别属于表A或表B,但我找不到它所说的“表C有一个外键到表A“具体而言。我可以弄清楚查询的细节,我只是找不到我正在寻找的视图(或者我正在掩饰它们)。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:36)

Courtesy of Pinal Dave:

SELECT 
    f.name AS ForeignKey,
    OBJECT_NAME(f.parent_object_id) AS TableName,
    COL_NAME(fc.parent_object_id,
    fc.parent_column_id) AS ColumnName,
    OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
    COL_NAME(fc.referenced_object_id,
    fc.referenced_column_id) AS ReferenceColumnName
FROM 
    sys.foreign_keys AS f
    INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id

答案 1 :(得分:0)

添加动态删除并在dbo方案上创建。

DECLARE @l varchar(1) = char(13);
DECLARE @referenced_object_id varchar(MAX) = 'Replace_With_PK_Table_Name';

SELECT 
    fk.name AS ForeignKey,
    OBJECT_NAME(fk.parent_object_id) AS TableName,
    COL_NAME(fkc.parent_object_id,
    fkc.parent_column_id) AS ColumnName,
    OBJECT_NAME (fk.referenced_object_id) AS ReferenceTableName,
    COL_NAME(fkc.referenced_object_id,
    fkc.referenced_column_id) AS ReferenceColumnName,
    'ALTER TABLE [dbo].['+OBJECT_NAME(fk.parent_object_id)+'] DROP CONSTRAINT ['+fk.name+'];' DropFK,
    'ALTER TABLE [dbo].['+OBJECT_NAME(fk.parent_object_id)+']  WITH NOCHECK ADD  CONSTRAINT ['+fk.name+'] FOREIGN KEY(['+COL_NAME(fkc.referenced_object_id,
    fkc.referenced_column_id)+'])'+ @l +
    ' REFERENCES [dbo].['+OBJECT_NAME(fk.referenced_object_id)+'] (['+COL_NAME(fkc.referenced_object_id,
    fkc.referenced_column_id)+'])'+ @l +
    ' ON UPDATE CASCADE'+ @l +
    ' ON DELETE CASCADE;'+ @l +
    'ALTER TABLE [dbo].['+OBJECT_NAME(fk.parent_object_id)+'] CHECK CONSTRAINT ['+fk.name+'];' CreateFK
FROM 
    sys.foreign_keys AS fk
    INNER JOIN sys.foreign_key_columns AS fkc ON fk.OBJECT_ID = fkc.constraint_object_id
    WHERE OBJECT_NAME(fk.referenced_object_id)=@referenced_object_id