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

前端 未结 11 1642
礼貌的吻别
礼貌的吻别 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条回答
  •  旧时难觅i
    2020-12-04 06:03

    Declare @FKeyRemoveQuery NVarchar(max)
    
    IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.TableName'))
    
    BEGIN
        SELECT @FKeyRemoveQuery='ALTER TABLE dbo.TableName DROP CONSTRAINT [' + LTRIM(RTRIM([name])) + ']'   
        FROM sys.foreign_keys
        WHERE parent_object_id = OBJECT_ID(N'dbo.TableName')
    
        EXECUTE Sp_executesql @FKeyRemoveQuery 
    
    END
    

提交回复
热议问题