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 2: Code Vulnerabilities due to SQL Server MisconceptionsSELECT @i AS [@i after the assignment] ;Listing 2-12: SELECT may leave a variable unchanged if it raises an error.Understanding how SET and SELECT behave is very important. In particular, thebehavior of SELECT demonstrated in Listing 2-9, whereby it leaves a variable unchangedif the selected result set is empty, can lead to the dreaded infinite loop.Use set-based solutions where possibleOf course, wherever possible we should avoid procedural, row-by-row processing inour T-SQL code, in favor of proper set-based aggregation. However, sometimes loopsare unavoidable.In order to demonstrate the infinite loop problem, create the Orders table shown inListing 2-13 and populate it with sample data.CREATE TABLE dbo.Orders(OrderID INT NOT NULL ,OrderDate DATETIME NOT NULL ,IsProcessed CHAR(1) NOT NULL ,CONSTRAINT PK_Orders PRIMARY KEY ( OrderID ) ,CONSTRAINT CHK_Orders_IsProcessedCHECK ( IsProcessed IN ( 'Y', 'N' ) )) ;GOINSERT dbo.Orders( OrderID ,OrderDate ,IsProcessed)SELECT 1 ,'20090420' ,'N'UNION ALL67

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

Saved successfully!

Ooh no, something went wrong!