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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 3: Surviving Changes to <strong>Database</strong> ObjectsDECLARE @CustomerId INT ;SELECT @CustomerId = CustomerIdFROM dbo.CustomersWHERE PhoneNumber = '(123)456-7890' ;SELECT @CustomerId AS CustomerId ;-- Do something with CustomerIdListing 3-11: Unpredictable variable assignment, using SELECT.In our original database schema, before we added CountryCode column to theCustomers table, the result of this assignment was predictable. However, in our newschema, the UNQ_Customers constraint only guarantees the uniqueness of the valuesin the PhoneNumber and CountryCode columns, considered together. As a result,we have two customers with this phone number and so the variable assignment isunpredictable; we do not, and cannot, know which of the two CustomerId values,1 or 3, will populate the variable.In most cases, such ambiguity is not acceptable. The simplest fix is to use SET instead ofSELECT to populate the variable, as shown in Listing 3-12.DECLARE @CustomerId INT ;-- this assignment will succeed,-- because in this case there is no ambiguitySET @CustomerId = ( SELECT CustomerIdFROM dbo.CustomersWHERE PhoneNumber = '(234)123-4567') ;SELECT @CustomerId AS CustomerId ;CustomerId-----------287

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

Saved successfully!

Ooh no, something went wrong!