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 2: Code Vulnerabilities due to SQL Server Misconceptions-- this call processes 3 orders and then completesEXEC dbo.ProcessBatchOfOrders 10 ;Listing 2-18: Invoking the fixed procedure.Alternatively, we can fix this problem by replacing the SELECT with a SET assignment,as shown in Listing 2-19.ALTER PROCEDURE dbo.ProcessBatchOfOrders @IDsIntervalSize INTASDECLARE @minID INT ,@ID INT ;SELECT @minID = MIN(OrderID) ,@ID = MIN(OrderID)FROM dbo.Orders ;WHILE @ID < ( @minID + @IDsIntervalSize )BEGIN;UPDATE dbo.OrdersSET IsProcessed = 'Y'WHERE OrderID = @ID ;-- SELECT is replaced with SETSET @ID = ( SELECT TOP (1)OrderIDFROM dbo.OrdersWHERE IsProcessed = 'N'ORDER BY OrderID) ;-- PRINT is needed for debugging purposesPRINT @ID ;END ;Listing 2-19: Replacing the SELECT with a SET removes the infinite loop.We can rerun Listing 2-18 to verify that the procedure works.71

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

Saved successfully!

Ooh no, something went wrong!