Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Check Constraint

Author  Topic 

rohaandba
Starting Member

33 Posts

Posted - 2012-04-17 : 16:48:47
I have a table with 3 columns

A int Null
B int Null
C int Not Null -- Cloumn 'C' can have only 2 values 150 & 151

I need to create a Check Constraint with the conditions

if value in Column 'C' is 150 then Column 'A' should have a value for sure (ie IS Not Null)
if value in Column 'C' is 151 then Column 'B' should have a value for sure (ie IS Not Null)

Can any one help me how to create this perticular check constraint, and if needed a function also.

robvolk
Most Valuable Yak

15732 Posts

Posted - 2012-04-17 : 17:06:13
ALTER TABLE myTable ADD CONSTRAINT CK_Values CHECK ((C=150 AND A IS NOT NULL) OR (C=151 AND B IS NOT NULL))
Go to Top of Page

rohaandba
Starting Member

33 Posts

Posted - 2012-04-17 : 17:41:02
Thanks you very much,

Is there any way
if the Column 'C' is allowed to have other values than 150 & 151
In That perticular senario both columns A & B can accept nulls.

How could I change this check constraint.
Go to Top of Page

robvolk
Most Valuable Yak

15732 Posts

Posted - 2012-04-17 : 17:48:21
ALTER TABLE myTable ADD CONSTRAINT CK_Values CHECK (C NOT IN (150,151) OR (C=150 AND A IS NOT NULL) OR (C=151 AND B IS NOT NULL))
Go to Top of Page
   

- Advertisement -