Khuzema Kamaal
Khuzema Kamaal

Reputation: 321

Conditional foreign key in SQL

i have one table called as PartyChannel having following columns

 ID, ChannelID, ChannelType

ChannelID stores MailID or PhoneID or EmailID depending on the ChannelType.

so how can i create a foreign key between PartyChannel and all three tables (Mail, Email and Phone) depending on the channelType.

Upvotes: 19

Views: 13086

Answers (3)

Damir Sudarevic
Damir Sudarevic

Reputation: 22187

Sub-type Email, Mail, Phone to the Channel.

alt text

Upvotes: 8

Lieven Keersmaekers
Lieven Keersmaekers

Reputation: 58431

You can use PERSISTED COMPUTED columns with a case statement but in the end, it buys you nothing but overhead.

The best solution would be to model them as three distinct values to start with.

CREATE TABLE Mails (MailID INTEGER PRIMARY KEY)
CREATE TABLE Phones (PhoneID INTEGER PRIMARY KEY)
CREATE TABLE Emails (EmailID INTEGER PRIMARY KEY)

CREATE TABLE PartyChannel (
  ID INTEGER NOT NULL
  , ChannelID INTEGER NOT NULL
  , ChannelType CHAR(1) NOT NULL
  , MailID AS (CASE WHEN [ChannelType] = 'M' THEN [ChannelID] ELSE NULL END) PERSISTED REFERENCES Mails (MailID)
  , PhoneID AS  (CASE WHEN [ChannelType] = 'P' THEN [ChannelID] ELSE NULL END) PERSISTED REFERENCES Phones (PhoneID)
  , EmailID AS  (CASE WHEN [ChannelType] = 'E' THEN [ChannelID] ELSE NULL END) PERSISTED REFERENCES Emails (EmailID)
)

Disclaimer

just because you can doesn't mean you should.

Upvotes: 19

Mark Brittingham
Mark Brittingham

Reputation: 28865

AFAIK, you cannot do this with standard foreign keys. However, you could implement something to help ensure data integrity by using triggers. Essentially, the trigger would check for the presence of a "foreign key" on the referenced table - the value that must be present - whenever there is an insert or update on the referencing table. Similarly, a delete from the referenced table could have a trigger that checks for records on the referencing table that use the key being deleted.

Update: Although I went right for the "answer" I agree with the comment left by @onedaywhen that this is actually a design-caused problem that should probably make you reconsider your design. That is, you should have three different columns rather than one column referencing three tables. You would just leave the other two columns null when one is filled which, in turn, would let you use standard foreign keys. Any concern that this would "use too much space" is silly; it represents a severe case of premature optimization - it just isn't going to matter.

Upvotes: 4

Related Questions