-2

I have a table full of data and I have a constraint on a field in that table that is setup to ensure the total of 2 fields equals a 3rd field. For example:

ALTER TABLE [dbo].[Table1]
WITH NOCHECK ADD CONSTRAINT [CHK_TOTALS] CHECK ([Field3] = [Field1] + [Field2])

If I then check this constraint:

ALTER TABLE [dbo].[Table1]
CHECK CONSTRAINT [CHK_TOTALS]

No errors are returned, the operation executes successfully, therefore it is as though all rows are satisfying the constraint.

However, if I then execute DBCC CHECKCONSTRAINTS([Table1]) several rows are returned for constraint CHK_TOTALS showing that there are multiple breaches of the constraint.

I have checked the data and can confirm that [Field1] + [Field2] does not total [Field3] for all rows.

Why does the first check not identify these but using DBCC CHECKCONSTRAINTS does?

  • 2
    You're missing a check when you enable the constraint: ALTER TABLE dbo.Table1 WITH CHECK CHECK CONSTRAINT CHK_TOTALS; – Erik Darling Jul 6 at 17:14
2

ALTER TABLE [dbo].[Table1] CHECK CONSTRAINT [CHK_TOTALS] enables the constraint for all future updates to the table. Since you originally created that constraint WITH NOCHECK, existing at that time rows were not verified, and this applies (emphasis mine):

WITH CHECK | WITH NOCHECK

Specifies whether the data in the table is or isn't validated against a newly added or re-enabled FOREIGN KEY or CHECK constraint. If you don't specify, WITH CHECK is assumed for new constraints, and WITH NOCHECK is assumed for re-enabled constraints.

In other words, unless you explicitly specify WITH CHECK, existing rows won't be verified when you enable the constraint.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.