Search This Blog

Tuesday 17 February 2015

Difference between Cursor vs. while loop in SQL Server?

Step 1:- Create the table.

Create table #TestEmpRecord
(
       Row_No int identity,
       EmpID varchar(10),
       EmpName varchar(50)
)

insert into #TestEmpRecord(
EmpID,EmpName
)
select 'E001','Employee 1' union
select 'E002','Employee 2' union
select 'E003','Employee 3' union
select 'E004','Employee 4' union
select 'E005','Employee 5' union
select 'E006','Employee 6'


Step 2:- Using Cursor Print EmpId


declare @EmpID varchar(10)       --Declaring Variable
declare curTblwstp Cursor For    --Declaring Cursor
select EmpID from #TestEmpRecord --Select Record and Storing in Cursor
open curTblwstp                  --Open Cursor
fetch next from curTblwstp into @EmpID --Store Next Record In @EmpID
While @@Fetch_Status = 0
begin
  print @EmpID

  fetch next from curTblwstp into @EmpID --Store Next Record In @EmpID                                                    Using Loop
end

Close curTblwstp                --Close Cursor
Deallocate curTblwstp           --Deallocate Cursor


Step 3:- Using while loop Print EmpId


declare @EmpID varchar(10)
declare @RowCount int
declare @I int

set @RowCount = 0
set @I = 1

set @RowCount = (select count(*) from #TestEmpRecord)

while(@I <= @RowCount)
begin
       set @EmpID = (select EmpID from #TestEmpRecord where Row_No = @I)

       print @EmpID

       set @I = @I + 1
end

Note:-

Based on the above example, both are doing the same thing and execution time also takes same. You need to decide either while loop or cursor based on your requirement.

No comments:

Post a Comment