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> Objectsconsider the case of an uncorrelated subquery that becomes correlated because acolumn from a table in the subquery is removed (or misspelled in the query), buthappens to match a column in the outer query. Many developers forget that the parserwill look in the outer query if it fails to find a match in the inner query.Handling changes in nullability: NOT IN versusNOT EXISTSQueries with NOT IN have a well known vulnerability. They do not work as aninexperienced database programmer might expect, if the subquery contained in theNOT IN clause returns at least one NULL. This is easy to demonstrate. In Listing 3-21,we recreate our ShipmentItems table with a Barcode column that does notaccept NULLs, and then insert some fresh data. We then execute a query that usesthe NOT IN clause.DROP TABLE dbo.ShipmentItems ;GOCREATE TABLE dbo.ShipmentItems(ShipmentBarcode VARCHAR(30) NOT NULL ,Description VARCHAR(100) NULL ,Barcode VARCHAR(30) NOT NULL) ;GOINSERT INTO dbo.ShipmentItems( ShipmentBarcode ,Barcode ,Description)SELECT '123456' ,'1010203' ,'Some cool widget'UNION ALL95

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

Saved successfully!

Ooh no, something went wrong!