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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 7: Advanced Use of ConstraintsSELECT *FROM dbo.Tickets-- restoring test data to its original stateROLLBACK ;Listing 7-19: Trying to reopen a ticket assigned to Justin.We have seen how three constraints work together to enforce a rather complex businessrule. Originally, we used an approach that works in the simplest possible way, and thenwe modified it to be more efficient. We have also removed the side effect of changes inDevelopers.DeveloperID column propagating into the Tickets table (and our FKconstraint will prohibit changes that would result in orphaned rows).Let's move on to discuss another case where constraints really shine: inventory systems.Constraints and Rock Solid Inventory SystemsIn the previous example, we used constraints to improve a trigger-based solutiondiscussed in Chapter 4. This next example is completely new and involves an inventorysystem that is used to store the history of changes to an inventory of items. Listing 7-20creates the InventoryLog table, for this purpose.CREATE TABLE dbo.InventoryLog(-- In a real production system-- there would be a foreign key to the Items table.-- We have skipped it to keep the example simple.ItemID INT NOT NULL ,ChangeDate DATETIME NOT NULL ,ChangeQuantity INT NOT NULL ,-- in a highly concurrent system-- this combination of columns-- might not be unique, but let us keep-- the example simple227

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

Saved successfully!

Ooh no, something went wrong!