How to check if a Constraint exists in Sql server?

前端 未结 13 2006
无人及你
无人及你 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:31

    Just something to watch out for......

    In SQL Server 2008 R2 SSMS, the "Script Constraint as -> DROP And CREATE To" command produces T-SQL like below

    USE [MyDatabase]
    GO
    
    IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DEF_Detail_IsDeleted]') AND type = 'D')
    BEGIN
    ALTER TABLE [Patient].[Detail] DROP CONSTRAINT [DEF_Detail_IsDeleted]
    END
    
    GO
    
    USE [MyDatabase]
    GO
    
    ALTER TABLE [Patient].[Detail] ADD  CONSTRAINT [DEF_Detail_IsDeleted]  DEFAULT ((0)) FOR [IsDeleted]
    GO
    

    Out of the box, this script does NOT drop the constraint because the SELECT returns 0 rows. (see post Microsoft Connect).

    The name of the default constraint is wrong but I gather it also has something to do with the OBJECT_ID function because changing the name doesn't fix the problem.

    To fix this, I removed the usage of OBJECT_ID and used the default constraint name instead.

    (SELECT * FROM dbo.sysobjects WHERE [name] = (N'DEF_Detail_IsDeleted') AND type = 'D')
    

提交回复
热议问题