Conditional foreign key in SQL

前端 未结 3 1020
时光取名叫无心
时光取名叫无心 2021-02-05 14:37

i have one table called as PartyChannel having following columns

 ID, ChannelID, ChannelType

ChannelID stores MailID

3条回答
  •  渐次进展
    2021-02-05 15:08

    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.

提交回复
热议问题