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 6: Common Problems with Data Integrity(snip)ItemLabel OldBarcode NewBarcode--------------- -------------------- --------------------Flashlight 234567 2345679Lamp 123457 1234579Listing 6-50: Our altered trigger properly handles multi-row updates.The first lesson here is that, when developing triggers, the defensive programmer shouldalways use proper set-based logic, rather than iterative logic.Mishandling updates that affect the primary keyWe have fixed one problem in our trigger, but it has another serious bug; it doesnot handle the case when the primary key column is also modified. Listing 6-51demonstrates the problem. This time, the code also updates the ItemLabel column,which forms part of our Primary Key, as well as the Barcode column.BEGIN TRAN ;DELETE FROM dbo.ItemBarcodeChangeLog ;UPDATE dbo.ItemsSET ItemLabel = ItemLabel + 'C' ,Barcode = Barcode + '9' ;SELECT ItemLabel ,OldBarcode ,NewBarcodeFROM dbo.ItemBarcodeChangeLog ;ROLLBACK ;debugging output: data before updateItemLabelBarcode------------------------------ ---------------------------Lamp 123457200

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

Saved successfully!

Ooh no, something went wrong!