How to check if a Constraint exists in Sql server?

前端 未结 13 2011
无人及你
无人及你 2020-11-29 15:03

I have this sql:

ALTER TABLE dbo.ChannelPlayerSkins
    DROP CONSTRAINT FK_ChannelPlayerSkins_Channels

but apparently, on some other databa

13条回答
  •  庸人自扰
    2020-11-29 15:40

    You can use the one above with one caveat:

    IF EXISTS(
        SELECT 1 FROM sys.foreign_keys 
        WHERE parent_object_id = OBJECT_ID(N'dbo.TableName') 
            AND name = 'CONSTRAINTNAME'
    )
    BEGIN 
        ALTER TABLE TableName DROP CONSTRAINT CONSTRAINTNAME 
    END 
    

    Need to use the name = [Constraint name] since a table may have multiple foreign keys and still not have the foreign key being checked for

提交回复
热议问题