How do I drop a foreign key constraint only if it exists in sql server?

前端 未结 11 1621
礼貌的吻别
礼貌的吻别 2020-12-04 05:34

I can drop a table if it exists using the following code but do not know how to do the same with a constraint:

IF EXISTS(SELECT 1 FROM sys.objects WHERE OBJE         


        
11条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 05:59

    The more simple solution is provided in Eric Isaacs's answer. However, it will find constraints on any table. If you want to target a foreign key constraint on a specific table, use this:

    IF EXISTS (SELECT * 
      FROM sys.foreign_keys 
       WHERE object_id = OBJECT_ID(N'dbo.FK_TableName_TableName2')
       AND parent_object_id = OBJECT_ID(N'dbo.TableName')
    )
      ALTER TABLE [dbo.TableName] DROP CONSTRAINT [FK_TableName_TableName2]
    

提交回复
热议问题