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 Constrain Based on Another Column

Author  Topic 

user79
Starting Member

2 Posts

Posted - 2012-05-04 : 00:25:49
Hi i have Table A - Column A,Column B

Column B can not be a null value if Coulmn A = "xxx", how can i do this.

Thanks.

user79
Starting Member

2 Posts

Posted - 2012-05-04 : 03:10:06
alter table Contacts
add constraint chkRegion CHECK ((REGION IS NOT NULL AND Country = 'USA') OR (REGION IS NULL AND Country <> 'USA') OR (REGION IS NOT NULL AND Country <> 'USA'))
Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2012-05-04 : 13:47:09
Hu?
REGION IS NOT NULL AND Country = 'USA' 
REGION IS NOT NULL AND Country <> 'USA'
Go to Top of Page

RL
Starting Member

15 Posts

Posted - 2012-05-04 : 15:56:18
Cleaner way to express the same logic:


alter table Contacts
add constraint chkRegion CHECK (country <> 'USA' OR region IS NOT NULL);


INSERT INTO Contacts SELECT 'USA', NULL; -- FAILS
INSERT INTO Contacts SELECT 'USA', 'East' -- OK;
INSERT INTO Contacts SELECT 'CAN', NULL; -- OK
INSERT INTO Contacts SELECT NULL, NULL; -- OK

Go to Top of Page
   

- Advertisement -