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.InventoryLogADD CONSTRAINT CHK_InventoryLog_ValidPreviousChangeDateCHECK(PreviousChangeDate < ChangeDateOR PreviousChangeDate IS NULL) ;Listing 7-26: CHK_InventoryLog_ValidPreviousChangeDate –PreviousChangeDate must occur before ChangeDate.Clearly, for a given item, the current value for PreviousQuantity must match theprevious value for CurrentQuantity. We'll use a FOREIGN KEY constraint, plus therequired UNIQUE constraint or index, to enforce this rule. At the same time, this will alsoensure that the PreviousChangeDate is a date that actually has an inventory changefor the same item.ALTER TABLE dbo.InventoryLogADD CONSTRAINT UNQ_InventoryLog_WithQuantityUNIQUE( ItemID, ChangeDate, CurrentQuantity ) ;GOALTER TABLE dbo.InventoryLogADD CONSTRAINT FK_InventoryLog_SelfFOREIGN KEY( ItemID, PreviousChangeDate, PreviousQuantity )REFERENCES dbo.InventoryLog( ItemID, ChangeDate, CurrentQuantity );Listing 7-27: The FK_InventoryLog_Self FK constraint.With these four constraints in place, in addition to our PRIMARY KEY constraint andoriginal CHECK constraint (CHK_InventoryLog_NonnegativeCurrentQuantity),it's about time to run some tests.Adding new rows to the end of the inventory trailThe simplest test case, is to INSERT new rows at the end of the inventory trail. First, let'sadd an initial inventory row for each of two items, as shown in Listing 7-28.237

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

Saved successfully!

Ooh no, something went wrong!