Objects in this mirror are closer to Microsoft Technologies. DNM objective is to help users on Microsoft technologies by providing Articles, snippets, Interview Questions.

15 September 2012

Iterating/Looping through rows without using cursors in Sql server


In this snippet we will see how to  iterating the table rows data with out using cursor in SQL server.
 
set nocount on
go

declare @tempEmpTable table(EmpID int , EmpName nvarchar(100))
declare  @varEmpID int, @varEmpName nvarchar(100)

insert into @tempEmpTable
select 1, '1st Employee' union all
select 2, '2nd Employee' union all
select 3, '3rd Employee' union all
select 4, '4th Employee' union all
select 5, '5th Employee' union all
select 6, '6th Employee' union all
select 7, '7th Employee' union all
select 8, '8th Employee' union all
select 9, '9th Employee'

select top 1 @varEmpID = EmpID, @varEmpName = EmpName  from @tempEmpTable  

while @varEmpID is not null
begin
                print @varEmpName
                delete  @tempEmpTable   where @varEmpID = EmpID
                set @varEmpID = null         
                select top 1 @varEmpID = EmpID, @varEmpName = EmpName  from @tempEmpTable  
end
Output:
1st Employee
2nd Employee
3rd Employee
4th Employee
5th Employee
6th Employee
7th Employee
8th Employee
9th Employee

1 Comments:

Satish With U said...

Good one

Post a Comment