代码之家  ›  专栏  ›  技术社区  ›  Ian Boyd

SQL Server:如何使服务器检查其所有检查约束?

  •  24
  • Ian Boyd  · 技术社区  · 15 年前

    看起来有些由EnterpriseManager*生成的脚本(或者不重要)创建了检查约束 用NOCHECK .

    现在,当有人修改表时, SQL Server is stumbling across failed check constraints ,并引发错误。

    我可以让SQL遍历所有的检查约束并检查它们吗?

    运行:

    sp_msforeachtable 'ALTER TABLE ? CHECK CONSTRAINT all'
    

    只启用以前禁用的检查约束,而不实际检查它们。

    脚注

    *SQL Server 2000

    3 回复  |  直到 7 年前
        1
  •  49
  •   Ian Boyd    12 年前

    带所有\约束的DBCC CHECKCONSTRAINTS 实际上不会使您的约束可信。它将报告任何违反约束的行。要使所有约束都可信,可以执行以下操作:

    DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS --This reports any data that violates constraints.
    
    --This reports all constraints that are not trusted
    SELECT OBJECT_NAME(parent_object_id) AS table_name, name, is_disabled  
    FROM sys.check_constraints 
    WHERE is_not_trusted = 1
    UNION ALL
    SELECT OBJECT_NAME(parent_object_id) AS table_name, name, is_disabled  
    FROM sys.foreign_keys
    WHERE is_not_trusted = 1
    ORDER BY table_name
    

    在SQL Server 2000中,可以找到任何不受信任的约束:

    --Reports all constraints that are not trusted (SQL 2000)
    SELECT name, type, status,
        (status & 2048) AS IsTrusted,
        (status & 256) AS IsEnabled,
        OBJECTPROPERTY(id,'CnstIsNotTrusted') as is_not_trusted,
        OBJECTPROPERTY(id,'CnstIsDisabled') as is_disabled
    FROM sysobjects 
    WHERE type IN ('C', 'F') --C=Constraint, F=Foreign Key
    AND OBJECTPROPERTY(id,'CnstIsNotTrusted') <> 0
    AND OBJECTPROPERTY(id,'CnstIsDisabled') = 0
    

    然后重新启用约束 用支票 :

    --This makes all constraints trusted
    -- but first anything reported by DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS must be fixed.
    exec sp_msforeachtable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all'
    

    注释 :在最后一条语句中, WITH CHECK CHECK 不是打字。“WITH CHECK”将检查所有表数据以确保没有冲突,并将使约束可信,而检查将确保启用约束。

    参见: http://sqlblog.com/blogs/tibor_karaszi/archive/2008/01/12/non-trusted-constraints.aspx

    http://sqlblog.com/blogs/tibor_karaszi/archive/2008/01/12/non-trusted-constraints-and-performance.aspx

        2
  •  8
  •   Ian Boyd    13 年前

    Found it :

    检查当前数据库中所有表上的所有约束,无论是否启用该约束:

    DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS
    

    要仅检查启用的约束:

    DBCC CHECKCONSTRAINTS
    
        3
  •  4
  •   Community CDub    6 年前

    这样做:

    ALTER TABLE dbo.Test
          WITH CHECK CHECK CONSTRAINT CK_Test;
    

    说明: Can you trust your constraints?