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 IntegrityAs a result, our CHECK constraint provides a false negative; it erroneously prohibited aperfectly valid multi-row update. Note that the behavior described here is arguably a bugin SQL Server. As such, it could be fixed in future versions of SQL Server.False positives: allowing an invalid modificationWith this technique, a more common problem than the false negative is the falsepositive, i.e. allowing an invalid modification. This problem occurs because peopleforget that CHECK constraints only fire if the columns they protect are modified. Todemonstrate this, we need to change the implementation of our scalar UDF and rewrapit in a CHECK constraint, as shown in Listing 6-38. Before the change, the UDF tookBarcode as a parameter; now it takes ItemLabel.ALTER TABLE dbo.ItemsDROP CONSTRAINT UNQ_Items_Barcode ;GOALTER FUNCTION dbo.GetBarcodeCount( @ItemLabel VARCHAR(30) )RETURNS INTASBEGIN ;DECLARE @barcodeCount INT ;SELECT @barcodeCount = COUNT(*)FROM dbo.Items AS i1INNER JOIN dbo.Items AS i2ON i1.Barcode = i2.BarcodeWHERE i1.ItemLabel = @ItemLabel ;RETURN @barcodeCount ;END ;GOALTER TABLE dbo.ItemsADD CONSTRAINT UNQ_Items_BarcodeCHECK ( dbo.GetBarcodeCount(ItemLabel) < 2 ) ;GOListing 6-38: Modifying the GetBarcodeCount scalar UDF and CHECK constraint.188

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

Saved successfully!

Ooh no, something went wrong!