Wednesday, 3 June 2015

Read data in sql row by row and perform actions per each record using curssor or while

=>We can repeat data in sql server and perform actions records by records.

=> Two main ways we can do (1) using cursor (2) While

=> The best way is using while insted of cursor. if we use cursor it user some extra resources like closing the cursor and deallocate the  cursor so it increase the query execution plan.

Ex. Cursor
==============================================================
DECLARE @ItemId INT,@PanelId INT,@LabelText VARCHAR(1000),@MinId int

DECLARE MYCURSOR CURSOR
FOR SELECT  ItemId,PanelId,LabelText FROM config_panelxitems

OPEN MYCURSOR
FETCH NEXT FROM MYCURSOR INTO @ItemId,@PanelId,@LabelText

WHILE @@FETCH_STATUS=0
BEGIN

PRINT @LabelText

FETCH NEXT FROM MYCURSOR INTO @ItemId,@PanelId,@LabelText
END

CLOSE MYCURSOR
DEALLOCATE MYCURSOR

Ex. While
==============================================================

DECLARE @ItemId INT,@PanelId INT,@LabelText VARCHAR(1000),@MinId int

SET @MinId=(select min(ItemId) from config_panelxitems)

WHILE @MinId IS NOT NULL
BEGIN

 SELECT @LabelText=LabelText FROM config_panelxitems WHERE ItemId=@MinId

 PRINT @LabelText
 SET @MinId=(select min(ItemId) from config_panelxitems WHERE ItemId>@MinId)
END

No comments:

Post a Comment