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 4: When Upgrading Breaks CodeBEGIN CATCH ;SELECT ERROR_MESSAGE() ;ROLLBACK ;END CATCH ;Cannot Delete More Than One RowListing 4-26: The MERGE command intends to delete only one row (and to modifyanother one) but falls foul of our trigger. These commands run only onSQL 2008 and upwards.Let us drop the trigger altogether, as shown in Listing 4-27.DROP TRIGGER dbo.CannotDeleteMoreThanOneArticle ;Listing 4-27: Dropping the trigger before rerunning the MERGE command.And now we can rerun the code from Listing 4-26 and see that this MERGE commandmodified one row and deleted only one row, so it should not have failed.We have proved that, when we start using MERGE, some of our triggers maymalfunction. Again, assuming this trigger was developed prior to SQL Server 2008,I would argue that there is little the developer could have done at the time to anticipatethat it might no longer work in a later version. However, at the point where we upgradeto SQL Server 2008, the defensive programmer must get to work investigating how theuse of MERGE might affect existing code, and fixing the issues that are found.In this case, the fix is quite straightfoward, as shown in Listing 4-28. Rather than rely on@@ROWCOUNT, we simply query the deleted table to ensure that we are not deletingmore than one row at a time.CREATE TRIGGER CannotDeleteMoreThanOneArticleON dbo.FrontPageArticlesFOR DELETEASBEGIN ;128

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

Saved successfully!

Ooh no, something went wrong!