Can you replace or update a SQL constraint?

StormPooper picture StormPooper · May 14, 2009 · Viewed 52.8k times · Source

I have written the following constraint for a column I've called 'grade':

CONSTRAINT gradeRule CHECK grade IN (‘easy’, ‘moderate’, ‘difficult’),

Is it possible to later update the gradeRule to have different values? For example, 'moderate' and 'difficult' could be changed to 'medium' and 'hard'.

Thanks

Answer

Scott Ivey picture Scott Ivey · May 14, 2009

You could drop the existing constraint, and add the new constraint with the NOCHECK option. This would allow you to add the constraint even though data in the table violates the constraint. The problem with doing this though would be that you wouldn't be able to update existing records without making them pass the constraint first.

ALTER TABLE SomeTable DROP CONSTRAINT gradeRule
GO
ALTER TABLE SomeTable ADD CONSTRAINT gradeRule ... WITH NOCHECK
GO

Although this is possible, its not usually recommended because of the potential problems with future updates of the data.