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 ConstraintsMsg 1776, Level 16, State 0, Line 1There are no primary or candidate keys in the referencedtable 'dbo.Developers' that match the referencing column listin the foreign key 'FK_Tickets_Developers_WithStatus'.Msg 1750, Level 16, State 0, Line 1Could not create constraint. See previous errors.Listing 7-4: A very clear error message.As the error states, the column, or combination of columns, to which a FOREIGN KEYrefers in the parent table, in this case (DeveloperID, DeveloperStatus), must beunique. The uniqueness can be enforced very easily using a UNIQUE constraint or, asshown in Listing 7-5, a UNIQUE index.CREATE UNIQUE INDEX UNQ_Developers_IDWithStatusON dbo.Developers( DeveloperID, DeveloperStatus ) ;Listing 7-5: Enforcing the uniqueness of (DeveloperID, DeveloperStatus) inthe Developers table.The reason I chose to use an index here, rather than a constraint, is because I try to usethe latter strictly to enforce business rules, and the former for performance or otherissues. In this case, we are not enforcing a business rule (as DeveloperID by itself isalready a candidate key) so much as overcoming a SQL Server technicality, and thereforeI chose to use an index.Now Listing 7-3 will complete successfully. Before testing our solution, let's summarizethe changes we have made so far.• Added a new column, DeveloperStatus, to the Tickets table.• Added a CHECK constraint, CHK_Tickets_ValidStatuses, to enforce ourbusiness rules.• Created a UNIQUE index on (DeveloperID, DeveloperStatus) in theDevelopers table, which allowed these two columns to be used as the parentcolumns in a foreign key relationship.213

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

Saved successfully!

Ooh no, something went wrong!