zoukankan      html  css  js  c++  java
  • 数据库检查约束是否存在

    http://stackoverflow.com/questions/2499332/how-to-check-if-a-constraint-exists-in-sql-server

    Easiest way to check for the existence of a constraint (and then do something such as drop it if it exists) is to use the OBJECT_ID() function...

    IF OBJECT_ID('dbo.[CK_ConstraintName]', 'C') IS NOT NULL 
        ALTER TABLE dbo.[tablename] DROP CONSTRAINT CK_ConstraintName

    OBJECT_ID can be used without the second parameter ('C' for check constraints only) and that may also work, but if your constraint name matches the name of other objects in the database you may get unexpected results.

    IF OBJECT_ID('dbo.[CK_ConstraintName]') IS NOT NULL 
        ALTER TABLE dbo.[tablename] DROP CONSTRAINT CK_ConstraintName

    OBJECT_ID can also be used with other "constraints" such as Foreign Key constraints or Primary Key constraints, etc. For best results, always include the appropriate object type as the second parameter for the OBJECT_ID function:

    Constraint Object Types:

    • C = CHECK constraint
    • D = DEFAULT (constraint or stand-alone)
    • F = FOREIGN KEY constraint
    • PK = PRIMARY KEY constraint
    • R = Rule (old-style, stand-alone)
    • UQ = UNIQUE constraint

    Also note that the schema is often required. The schema of constraints generally takes the schema of the parent table.

    Failure to put your constraints (or whatever you are checking) in brackets when using this method may also cause a false negative -- if your object uses unusual characters (such as a .), the brackets are required.

  • 相关阅读:
    CTFHub_技能树_文件上传
    QT入门-重载的信号槽
    QT入门-自定义信号
    C++: xx does not name a type报错
    HDU1166 敌兵布阵
    洛谷P2574 XOR的艺术(线段树)
    P3373 【模板】线段树 2(板子好题)
    SP1716 GSS3
    QT入门-自定义槽函数
    Educational Codeforces Round 87 (Rated for Div. 2) D. Multiset(树状数组/好题)
  • 原文地址:https://www.cnblogs.com/wucg/p/6186377.html
Copyright © 2011-2022 走看看