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 IntegrityNewBarcodeEND ;)SELECT d.ItemLabel ,CURRENT_TIMESTAMP ,d.Barcode ,i.BarcodeFROM inserted AS iINNER JOIN deleted AS dON i.ItemLabel = d.ItemLabelWHERE ( ( d.Barcode i.Barcode )OR ( d.Barcode IS NULLAND i.Barcode IS NOT NULL)OR ( d.Barcode IS NOT NULLAND i.Barcode IS NULL)) ;Listing 6-52: Altering our trigger so that is does not allow modification of theprimary key column.To test this trigger, we can rerun Listings 6-48 and 6-51. If, however, our business rulesallow changes to be made to labels on items, then we need some other immutablecolumn; some column that cannot be changed, and so can uniquely identify a row.This is one of those cases when IDENTITY columns are so useful. Listing 6-53 adds anIDENTITY column and creates a UNIQUE constraint to make sure that the IDENTITYcolumn is always unique.ALTER TABLE dbo.ItemsADD ItemID int NOT NULLIDENTITY(1, 1) ;GO202

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

Saved successfully!

Ooh no, something went wrong!