Implementing a “Both, Either-or, but Not Null” Requirement in a Database

后端 未结 4 1499
谎友^
谎友^ 2021-01-21 16:11

I have requirement for a web app that states that a user should be able to either upload an instruction document(s) (.pdf, .doc, .txt) or provide text for the instructions. The

4条回答
  •  青春惊慌失措
    2021-01-21 17:01

    I think that this cannot be done with Declarative Referential Integrity alone - not if your design has these 3 separate tables.

    You'll have to ensure that all Insert/Delete/Update operations are done within transactions (stored procedures) that enforce such a requirement - so no row is ever inserted or left in table Instruction without a relative row in either one of the 2 other tables.


    If you don't mind having nullable fields, you could merge the 3 tables into one and use a CHECK constraint:

    CREATE TABLE Instruction
    ( InstructionID INT          NOT NULL
    , Text          VARCHAR(255) NULL
    , Filepath      VARCHAR(255) NULL
    , PRIMARY KEY (InstructionID)
    , CONSTRAINT Instruction_has_either_text_or_document 
        CHECK (Text IS NOT NULL OR FilePath IS NOT NULL)
    ) ;
    

提交回复
热议问题