A Simple Way to Fetch Data One by One using While Loop If Table has a Identity or Primary Key.

Assume that I am using below table and need to fetch one by one all rows and do some operation.

Table structure

CREATE TABLE [dbo].[User_Login](

[userid] [int] IDENTITY(1,1) NOT NULL,

[Username] [varchar](100) NULL,

[User_Pass] [varchar](100) NULL,

[F_Name] [varchar](20) NULL,

[L_Name] [varchar](20) NULL,

[Address1] [varchar](200) NULL,

[mobile] [varchar](20) NULL,

[City] [varchar](20) NULL

)

Query

declare @cnt int

declare @UnitCount int

set @cnt=1

set @UnitCount=(select count(*) from User_Login)

while @cnt<@UnitCount

begin

select top(1)* from User_Login where userid not in(select top(@cnt-1) userid from User_Login) order by userid

--Do your operation like fetch data into variables and update it into another table etc..

set @cnt=@cnt+1

end