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> Objects'Regular' ,'(123)456-7890'UNION ALLSELECT 2 ,'Peter' ,'Hansen' ,'Regular' ,'(234)123-4567' ;Listing 3-1: Creating the Customers table, with a UNIQUE constraint on thePhoneNumber column.We need to implement a simple stored procedure, shown in Listing 3-2, which will allowusers to find a customer based on their phone number, and set their customer status(regular, preferred, or VIP). If no customer exists for a given phone number, we don'tneed to raise an exception; we simply do nothing.CREATE PROCEDURE dbo.SetCustomerStatus@PhoneNumber VARCHAR(50) ,@Status VARCHAR(50)ASBEGIN;UPDATE dbo.CustomersSET Status = @StatusWHERE PhoneNumber = @PhoneNumber ;END ;Listing 3-2: The SetCustomerStatus stored procedure, which finds a customer byphone number and sets their status.This implementation assumes that at most one customer has any given phone number.Clearly, right now, this assumption is true as it is guaranteed by the UNQ_Customersconstraint.Suppose, however, that at some later time we need to store data about customersfrom different countries. At this point, the phone number alone no longer uniquelyindentifies a customer, but the combination of country code and phone number does.79

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

Saved successfully!

Ooh no, something went wrong!