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

前端 未结 11 1619
礼貌的吻别
礼貌的吻别 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:56

    The accepted answer on this question doesn't seem to work for me. I achieved the same thing with a slightly different method:

    IF (select object_id from sys.foreign_keys where [name] = 'FK_TableName_TableName2') IS NOT NULL
    BEGIN
        ALTER TABLE dbo.TableName DROP CONSTRAINT FK_TableName_TableName2
    END
    

提交回复
热议问题