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

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

    This gets any foreign key that involves the chosen table. *Assumes a _FIRSTABLENAME_SECONDTABLENAME format.

     declare @tablename as varchar(MAX)
     SET @tablename = 'yourtablename'
     SELECT name
     FROM YOURDATABASE.sys.objects
     WHERE type_desc = 'FOREIGN_KEY_CONSTRAINT' and (name LIKE '%_' + @tablename + 'empdb_%' or name LIKE '%_' + @tablename )
    

    This is a more general form:

     SELECT name
     FROM YOURDATABASE_PROD.sys.objects
     WHERE type_desc = 'FOREIGN_KEY_CONSTRAINT' and name LIKE '%' + @tablename + '%' and
     name NOT LIKE '[a-zA-Z0-9]' + @tablename + '%' and name NOT LIKE '%' + @tablename + '[a-zA-Z0-9]' 
    

提交回复
热议问题