At times you may need to sequentially loop through some specific result set for performing some action on individual record at a time.Using cursor is a choice, but we have other choices as well. Use following sample logic.
Example 1 - Loop Through Table Rows in SQL:
Select records where SalProcessed = 0 and process the logic.
Set the SalProcessed=1.
Continue loop Until count = 1
Declare @Id int
While (Select Count(1) From Emp Where SalProcessed = 0) > 0
Select Top 1 @Id = EmpId From Emp Where SalProcessed = 0
--Do the process of individual record here
Update Emp Set SalProcessed = 1 Where Id = @Id
Example 2 - Loop Through Table Rows in SQL :
Declare @Records INT= 0,
@Id int= 1,
-- Fetch total number of records to loop
Select @Records = Count(1) From dbo.Emp
While(@Id <= @Records)
-- select the required columns
Select@EmpName = EmpName
(Select ROW_NUMBER() over (Order By EmId asc) as RowNumber,
Where TempTbl.RowNumber = @Id
-- Process it here
-- increment Id by 1
@Id = @Id + 1
This article would have given you ideas on how to use a SELECT statement to loop through a set of records without using cursor to process one record at a time.
You can use Cursor also for looping through the record-set in T-SQL, but with select, it is simpler to code.You need to choose wisely among the two as per your requirement.Share your comments below.