SQL: Using Loop instead of Cursor

Sample 1:
~~~~~~
Declare @temp table
(
row_id int identity (1,1),
product varchar(50)
)

Declare @i int, @max int

Insert into #temp (product) Select product From products

set @max = @@rowcount
set @i = 1

While @i <= @max Begin Select product From #temp Where row_id = @i // Do your Processing here set @i = @i + 1 End Sample 2:
~~~~~~
DECLARE @Product VARCHAR(50)
DECLARE @ProductID INT -- I assume Product ID as primary Key

SELECT * INTO #Products FROM Products

WHILE EXISTS (SELECT * FROM #Products)
BEGIN
SET ROWCOUNT 1
SELECT @ProductID = ProductID, @Product = Product FROM #Products
SET ROWCOUNT 0

// Do your Processing here

DELETE #Products WHERE ProductID = @ProductID
END

No comments:

Post a Comment