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 3: Surviving Changes to <strong>Database</strong> ObjectsUsing @@ROWCOUNT to verify assumptionsAlternatively, instead of documenting our assumption as a unit test, we can have ourstored procedure detect how many rows it modified, and roll back if it updated morethan one row, as shown in Listing 3-9.ALTER PROCEDURE dbo.SetCustomerStatus@PhoneNumber VARCHAR(50) ,@Status VARCHAR(50)ASBEGIN ;BEGIN TRANSACTION ;UPDATE dbo.CustomersSET Status = @StatusWHERE PhoneNumber = @PhoneNumber ;IF @@ROWCOUNT > 1BEGIN ;ROLLBACK ;RAISERROR('More than one row updated',16, 1) ;END ;ELSEBEGIN ;COMMIT ;END ;END ;Listing 3-9: A stored procedure that will not modify more than one row.To see it in action, run Listing 3-10; the stored procedure raises an error and does notmodify the data.85

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

Saved successfully!

Ooh no, something went wrong!