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 IntegrityTriggers are dramatically more flexible than constraints, but we need to be very carefulwhen we use them. We need to make sure that they properly handle multi-row modifications,modifications of primary key columns, and snapshot isolation. Also we needto be aware that sometimes triggers do not fire, and to be ready to clean up data if thatactually happens.Following is a brief summary of the defensive techniques learned in this chapter withregard to protecting data integrity.• When testing CHECK constraints, always include in your test cases rows with NULLs.• Don't make assumptions about the data, based on the presence of FOREIGN KEY orCHECK constraints, unless they are all trusted.• UDFs wrapped in CHECK constraints are sometimes unreliable as a means to enforcedata integrity rules. Filtered Indexes or Indexed Views are safer alternatives.• When developing triggers:• always use proper set-based logic; never assume that only one row at a time canbe modified• if your code assumes that the primary key won't be modified, make sure that istrue, or use an IDENTITY column that is, by definition, immutable• query the sys.triggers system view to make sure there are no existing triggerson the table with which your one may interfere• make appropriate use of the READCOMMITTEDLOCK hint if the trigger needs torun under snapshot isolation levels.208

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

Saved successfully!

Ooh no, something went wrong!