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 IntegrityALTER TABLE dbo.ItemsWITH CHECKCHECK CONSTRAINT UNQ_Items_Barcode ;SELECT CAST(name AS char(20)) AS Name,is_disabled,is_not_trustedFROM sys.check_constraintsWHERE name = 'UNQ_Items_Barcode' ;Name is_disabled is_not_trusted-------------------- ----------- ---------------UNQ_Items_Barcode 0 0Listing 6-37: Re-enabling the constraint and making sure that it is trusted.Clearly, the CHECK constraint recognizes that, after the UPDATE, all the data inItems table is valid; otherwise the ALTER TABLE command would have failed andthe constraint would not be trustedSo, why did the constraint prevent a perfectly correct UPDATE from completing? Thereason, I believe, is as follows: CHECK constraints evaluate earlier than other types ofconstraint. As soon as a single row is modified, the CHECK constraint, UNQ_Items_Barcode, verifies that the modified row is valid. This verification occurs before otherrows are modified. In this particular case, two rows need to be modified. We do notknow which row is modified first but suppose, for the sake of argument, that it is therow with barcode 12345679. When this row is modified, the new barcode for that rowis 12345678. Immediately, the CHECK constraint, UNQ_Items_Barcode, invokes thescalar UDF, dbo.GetBarcodeCount, which returns 2, because there is another, as yetunmodified row with the same barcode, 12345678.NoteIn this particular case we are discussing an update that touches a very small tableand modifies only two rows. As such, we are not considering the possibility that thisupdate will execute on several processors in parallel.187

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

Saved successfully!

Ooh no, something went wrong!