views:

67

answers:

2

i want to check for a particular set of values.
eg

  • check columnname should be between 1 to 5
  • check columnname should be either 1 or 2 or 4
+1  A: 
ALTER TABLE tablename ADD CONSTRAINT constraintName CHECK (colname in (1,2,4));
chris
will it check for these values only
Shantanu Gupta
and what about checking for between a set of values i.e. between 1 to 5
Shantanu Gupta
sorry but ur answer is incomplete
Shantanu Gupta
dude, this isn't a test.
chris
+3  A: 

There is quite a wealth of information in the SQL Server documentation on this, but the two statements to create the check constraints you ask for are:

ALTER TABLE tablename ADD CONSTRAINT constraintName CHECK (colname between 1 and 5);

ALTER TABLE tablename ADD CONSTRAINT constraintName CHECK (colname in (1,2,4));

The condition of a check constraint can include:

  1. A list of constant expressions introduced with in

  2. A range of constant expressions introduced with between

  3. A set of conditions introduced with like, which may contain wildcard characters

This allows you to have conditions like:

(colname >= 1 AND colname <= 5)
David Hall
can we use regular expression also in check constraint.
Shantanu Gupta
Not as far as I know - a lot of what I wrote aboe comes from books online (the SQL Server documentation) and they don't mention that capability.
David Hall
thx a lot.Actually I am writing a question for my forum based on user "defined datatype" which need a database to be provided to user to understand. That question is little logical while dealing with storage+performance in Sql server. I will pass a link to that as soon as i prepares it to post.
Shantanu Gupta