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

后端 未结 26 2689
梦毁少年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: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

提交回复
热议问题