17.07.2015 Views

Defensive Database Programming - Red Gate Software

Defensive Database Programming - Red Gate Software

Defensive Database Programming - Red Gate Software

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 7: Advanced Use of ConstraintsALTER TABLE dbo.TicketsADD CONSTRAINT CHK_Tickets_ValidStatusesCHECK( (TicketStatus = 'Active'AND DeveloperStatus = 'Active')OR TicketStatus = 'Closed') ;Listing 7-2: The CHK_Tickets_ValidStatuses constraint enforces bothbusiness rules.However, this constraint makes a serious assumption, and we do not know yet ifwe can enforce it. Can we really guarantee that the Tickets.DeveloperStatuscolumn will always match the Developers.DeveloperStatus column, for theassigned developer?The answer is "maybe." FOREIGN KEY constraints are supposed to guarantee thatcolumns in different tables match and the one shown in Listing 7-3 attempts to do justthat. We'll discuss why we need the ON UPDATE CASCADE clause shortly.ALTER TABLE dbo.TicketsADD CONSTRAINT FK_Tickets_Developers_WithStatusFOREIGN KEY (AssignedToDeveloperID, DeveloperStatus)REFERENCES dbo.Developers( DeveloperID, DeveloperStatus )ON UPDATE CASCADE ;Listing 7-3: FK_Tickets_Developers_WithStatus attempts to ensure that,for a given developer, the relevant column values match.Unfortunately, when we run Listing 7-3, it fails. Fortunately, the error message is veryexplicit and clear.212

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!