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

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

    This is a lot simpler than the current proposed solution:

    IF (OBJECT_ID('dbo.FK_ConstraintName', 'F') IS NOT NULL)
    BEGIN
        ALTER TABLE dbo.TableName DROP CONSTRAINT FK_ConstraintName
    END
    

    If you need to drop another type of constraint, these are the applicable codes to pass into the OBJECT_ID() function in the second parameter position:

    C = CHECK constraint
    D = DEFAULT (constraint or stand-alone)
    F = FOREIGN KEY constraint
    PK = PRIMARY KEY constraint
    UQ = UNIQUE constraint
    

    You can also use OBJECT_ID without the second parameter.

    Full List of types here:

    Object type:

    AF = Aggregate function (CLR)
    C = CHECK constraint
    D = DEFAULT (constraint or stand-alone)
    F = FOREIGN KEY constraint
    FN = SQL scalar function
    FS = Assembly (CLR) scalar-function
    FT = Assembly (CLR) table-valued function
    IF = SQL inline table-valued function
    IT = Internal table
    P = SQL Stored Procedure
    PC = Assembly (CLR) stored-procedure
    PG = Plan guide
    PK = PRIMARY KEY constraint
    R = Rule (old-style, stand-alone)
    RF = Replication-filter-procedure
    S = System base table
    SN = Synonym
    SO = Sequence object
    

    Applies to: SQL Server 2012 through SQL Server 2014.

    SQ = Service queue
    TA = Assembly (CLR) DML trigger
    TF = SQL table-valued-function
    TR = SQL DML trigger
    TT = Table type
    U = Table (user-defined)
    UQ = UNIQUE constraint
    V = View
    X = Extended stored procedure
    

提交回复
热议问题