似乎企业管理器*生成的某些脚本(或没有,没关系)创建了检查约束WITH NOCHECK。
现在,当任何人修改表时,SQL Server 会遇到失败的检查约束,并引发错误。
我可以让 SQL 通过其所有检查约束并检查它们吗?
跑步:
sp_msforeachtable 'ALTER TABLE ? CHECK CONSTRAINT all'
仅启用之前禁用的检查约束,实际上并不检查它们。
* SQL Server 2000
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
然后重新启用约束并检查:
--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”将检查所有表数据以确保不存在违规,并使约束可信,同时检查将确保约束已启用。
另请参阅:
找到了:
检查当前数据库所有表的所有约束,无论约束是否启用:
DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS
仅检查启用的约束:
DBCC CHECKCONSTRAINTS