How can I list all foreign keys referencing a given table in SQL Server?

后端 未结 26 2635
梦毁少年i
梦毁少年i 2020-11-22 07:13

I need to remove a highly referenced table in a SQL Server database. How can I get a list of all the foreign key constraints I will need to remove in order to drop the tabl

相关标签:
26条回答
  • 2020-11-22 07:51

    You can find through below query :

     SELECT OBJECT_NAME (FK.referenced_object_id) 'Referenced Table', 
          OBJECT_NAME(FK.parent_object_id) 'Referring Table', FK.name 'Foreign Key', 
          COL_NAME(FK.referenced_object_id, FKC.referenced_column_id) 'Referenced Column',
          COL_NAME(FK.parent_object_id,FKC.parent_column_id) 'Referring Column'
         FROM sys.foreign_keys AS FK
                 INNER JOIN sys.foreign_key_columns AS FKC 
                     ON FKC.constraint_object_id = FK.OBJECT_ID
         WHERE OBJECT_NAME (FK.referenced_object_id) = 'YourTableName'
         AND COL_NAME(FK.referenced_object_id, FKC.referenced_column_id) = 'YourColumnName'
         order by  OBJECT_NAME(FK.parent_object_id)
    
    0 讨论(0)
  • 2020-11-22 07:52

    Not sure why no one suggested but I use sp_fkeys to query foreign keys for a given table:

    EXEC sp_fkeys 'TableName'
    

    You can also specify the schema:

    EXEC sp_fkeys @pktable_name = 'TableName', @pktable_owner = 'dbo'
    

    Without specifying the schema, the docs state the following:

    If pktable_owner is not specified, the default table visibility rules of the underlying DBMS apply.

    In SQL Server, if the current user owns a table with the specified name, that table's columns are returned. If pktable_owner is not specified and the current user does not own a table with the specified pktable_name, the procedure looks for a table with the specified pktable_name owned by the database owner. If one exists, that table's columns are returned.

    0 讨论(0)
  • 2020-11-22 07:53

    Some good answers above. But I prefer to have the answer with one query. This piece of code is taken from sys.sp_helpconstraint (sys proc)

    That's the way Microsoft looks up if there are foreign keys associated to the tbl.

    --setup variables. Just change 'Customer' to tbl you want
    declare @objid int,
        @objname nvarchar(776)
    select @objname = 'Customer'    
    select @objid = object_id(@objname)
    
    if exists (select * from sys.foreign_keys where referenced_object_id = @objid)
        select 'Table is referenced by foreign key' =
            db_name() + '.'
            + rtrim(schema_name(ObjectProperty(parent_object_id,'schemaid')))
            + '.' + object_name(parent_object_id)
            + ': ' + object_name(object_id)
        from sys.foreign_keys 
        where referenced_object_id = @objid 
        order by 1
    

    The answer will look like this: test_db_name.dbo.Account: FK_Account_Customer

    0 讨论(0)
  • 2020-11-22 07:54
    SELECT
      object_name(parent_object_id),
      object_name(referenced_object_id),
      name 
    FROM sys.foreign_keys
    WHERE parent_object_id = object_id('Table Name')
    
    0 讨论(0)
  • 2020-11-22 07:56

    I'd use the Database Diagramming feature in SQL Server Management Studio, but since you ruled that out - this worked for me in SQL Server 2008 (don't have 2005).

    To get list of referring table and column names...

    select 
        t.name as TableWithForeignKey, 
        fk.constraint_column_id as FK_PartNo, c.
        name as ForeignKeyColumn 
    from 
        sys.foreign_key_columns as fk
    inner join 
        sys.tables as t on fk.parent_object_id = t.object_id
    inner join 
        sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id
    where 
        fk.referenced_object_id = (select object_id 
                                   from sys.tables 
                                   where name = 'TableOthersForeignKeyInto')
    order by 
        TableWithForeignKey, FK_PartNo
    

    To get names of foreign key constraints

    select distinct name from sys.objects where object_id in 
    (   select fk.constraint_object_id from sys.foreign_key_columns as fk
        where fk.referenced_object_id = 
            (select object_id from sys.tables where name = 'TableOthersForeignKeyInto')
    )
    
    0 讨论(0)
  • 2020-11-22 07:58

    The original question asked to get a list of all foreign keys into a highly referenced table so that the table can be removed.

    This little query returns all the 'drop foreign key' commands needed to drop all foreign keys into a particular table:

    SELECT 
       'ALTER TABLE ['+sch.name+'].['+referencingTable.Name+'] DROP CONSTRAINT ['+foreignKey.name+']' '[DropCommand]'
    FROM sys.foreign_key_columns fk
        JOIN sys.tables referencingTable ON fk.parent_object_id = referencingTable.object_id
        JOIN sys.schemas sch ON referencingTable.schema_id = sch.schema_id
        JOIN sys.objects foreignKey ON foreignKey.object_id = fk.constraint_object_id
        JOIN sys.tables referencedTable ON fk.referenced_object_id = referencedTable.object_id
    WHERE referencedTable.name = 'MyTableName'
    

    Example output:

    [DropCommand]
    ALTER TABLE [dbo].[OtherTable1] DROP CONSTRAINT [FK_OtherTable1_MyTable]
    ALTER TABLE [dbo].[OtherTable2] DROP CONSTRAINT [FK_OtherTable2_MyTable]
    

    Omit the WHERE-clause to get the drop commands for all foreign keys in the current database.

    0 讨论(0)
提交回复
热议问题