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 > Foreign Key constraint where Not Null

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 12-08-10, 03:07
Wedgetail Wedgetail is offline
Registered User
 
Join Date: Feb 2009
Posts: 29
Foreign Key constraint where Not Null

Hi Forum,

I am relatively new to SQL and am trying to write a Table Constraint [Foreign Key], but have it only apply when one column is not NULL.

Here are the tables.

Contact
ContactID
PersonID
CompanyID

ContactOffice
ContactID
OfficeID
...

PhoneNumber
PhoneID
ContactID
OfficeID
PhoneNumber

The use case is:
A contact may or may not be assigned to an office.

As such, a Phone Number may be assigned to just the Contact [ie. No entry in the ContactOffice table], or to the Contact at the Office [ie. Entry in ContactOffice table].

I was looking to assign two Foreign Key constraints to the PhoneNumber table.

CONSTRAINT FOREIGN KEY ("ContactID") REFERENCES "Contact"("ContactID")

CONSTRAINT FOREIGN KEY ("ContactID","OfficeID") REFERENCES "ContactOffice"("ContactID","OfficeID")

However, I need to apply the second constraint only if NOT(OfficeID IS NULL). Am I after a CHECK constraint which references the ContactOffice table?

Could someone please help me with this constraint.
Reply With Quote
  #2 (permalink)  
Old 12-08-10, 04:41
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,524
Quote:
Originally Posted by Wedgetail View Post
However, I need to apply the second constraint only if NOT(OfficeID IS NULL).
you're fine the way it is

just ensure that the PK of ContactOffice is (ContactID,OfficeID)

since PKs must be not null, therefore (ContactID,OfficeID) in PhoneNumber can only reference ContactOffice when both columns are not null

if OfficeID is null, then the FK to ContactOffice doesn't apply
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
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