Question

I am trying to add a check constraint.

I first do

ALTER TABLE [Production].[Products]  WITH CHECK 
ADD  CONSTRAINT [CHK_Products_unitprice] CHECK  (([unitprice]>=(0)))
GO

which fails with the message

Msg 547, Level 16, State 0, Line 1
The ALTER TABLE statement conflicted with the CHECK constraint "CHK_Products_unitprice". The conflict occurred in database "TSQL2012", table "Production.Products", column 'unitprice'.

I then try adding the constraint without the "WITH CHECK" option and it still gives the above error.

So what is the point of the "with check" option then?

Was it helpful?

Solution

The default for creating new check constraints is the WITH CHECK option that will read and evaluate existing values, failing the ALTER if conflicts are found.

You can use WITH NOCHECK option if you need to deploy a check constraint that disregards existing existing bad values and you understand the downsides (see below), which is the default when enabling previously disabled constraints.

Please see the ALTER TABLE reference for details:

WITH CHECK | WITH NOCHECK

Specifies whether the data in the table is or is not validated against a newly added or re-enabled FOREIGN KEY or CHECK constraint. If not specified, WITH CHECK is assumed for new constraints, and WITH NOCHECK is assumed for re-enabled constraints.

If you do not want to verify new CHECK or FOREIGN KEY constraints against existing data, use WITH NOCHECK. We do not recommend doing this, except in rare cases. The new constraint will be evaluated in all later data updates. Any constraint violations that are suppressed by WITH NOCHECK when the constraint is added may cause future updates to fail if they update rows with data that does not comply with the constraint.

The query optimizer does not consider constraints that are defined WITH NOCHECK. Such constraints are ignored until they are re-enabled by using ALTER TABLE table WITH CHECK CHECK CONSTRAINT ALL.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top