If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Data Access, Manipulation & Batch Languages > ANSI SQL > Help with Constraint : Check two Columns NOT NULL

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 04-10-10, 06:01
Wedgetail Wedgetail is offline
Registered User
 
Join Date: Feb 2009
Posts: 29
Help with Constraint : Check two Columns NOT NULL [SOLVED]

Hi Forum,

I am trying to create a check constraint that checks that both EntityIDPerson and EntityIDCorp are not null.
There are three conditions that can be met as per the code below. ie.
1) Both EntityIDPerson and EntityIDCorp have a value.
2) EntityIDPerson has a value while EntityIDCorp is NULL.
3) EntityIDPerson is NULL while EntityIDCorp has a value.

However, if EntityIDPerson is NULL AND EntityIDCorp is Null then it should fail.

The check constraint below works. However, is there a simpler, cleaner way to write the constraint?

Code:
CREATE TABLE Contact (
	IDContact		        INT IDENTITY(1,1)	NOT NULL,
	EntityIDPerson		INT	NULL,
	EntityIDCorp		INT	NULL,
	ContactTypeID		INT	NOT NULL,	
	CONSTRAINT pk_Contact    PRIMARY KEY (IDContact),
        CONSTRAINT ck_Contact_EntityID	CHECK 
        (EntityIDPerson IS NOT NULL AND EntityIDCorp IS NOT NULL 
        OR EntityIDPerson IS NOT NULL AND EntityIDCorp IS NULL
        OR EntityIDPerson IS NULL AND EntityIDCorp IS NOT NULL)
        );

Last edited by Wedgetail; 04-10-10 at 06:43.
Reply With Quote
  #2 (permalink)  
Old 04-10-10, 06:37
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,524
how about...

CHECK ( NOT ( EntityIDPerson IS NULL AND EntityIDCorp IS NULL ) )


by the way, IDENTITY(1,1) is not ANSI SQL
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #3 (permalink)  
Old 04-10-10, 06:43
Wedgetail Wedgetail is offline
Registered User
 
Join Date: Feb 2009
Posts: 29
Thanks r937. I knew there must be a simple way but couldnt think of it.

And I know IDENTITY(1,1) is not ANSI SQL, but the actual question was ANSI SQL.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On