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

26

似乎一些由Enterprise Manager生成的脚本(或者不是,这并不重要)创建了WITH NOCHECK的检查约束。

现在,当任何人修改表时,SQL Server会遇到失败的检查约束并抛出错误

我是否可以让SQL遍历所有的检查约束,并对它们进行检查?

运行:

sp_msforeachtable 'ALTER TABLE ? CHECK CONSTRAINT all'

仅启用先前被禁用的检查约束,实际上并不检查它们。

脚注

* SQL Server 2000

3个回答

56

DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS实际上不会使您的约束条件获得信任。它将报告违反约束条件的任何行。要使所有约束条件真正受信任,您可以执行以下操作:

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

然后使用check重新启用了约束条件:

--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"将检查所有表数据以确保没有违规行为,并使约束受信任,而"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


9

找到它了

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

DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS

仅检查启用的约束:

DBCC CHECKCONSTRAINTS

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接