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

前端 未结 11 1641
礼貌的吻别
礼貌的吻别 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 06:08

    In SQL Server 2016 you can use DROP IF EXISTS:

    CREATE TABLE t(id int primary key, 
                   parentid int
                        constraint tpartnt foreign key references t(id))
    GO
    ALTER TABLE t
    DROP CONSTRAINT IF EXISTS tpartnt
    GO
    DROP TABLE IF EXISTS t
    

    See http://blogs.msdn.com/b/sqlserverstorageengine/archive/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016.aspx

提交回复
热议问题