While Loop With Example In SQL Server

While Loop With Example In SQL Server

All About SQL

1 год назад

146 Просмотров

Sometimes you have to iterate or loop through available data. SQL Server provide many looping techniques and i am explaining While loop with example here.


--While Loop in SQL Server
--select * from Employee

select ROW_NUMBER() over(order by EmpId) as Rn, * into #Emp from Employee

Declare @TotalCount int, @Counter int, @EmpId int, @EmpName varchar(100), @Salary int
select @TotalCount=COUNT(1) from #Emp
Set @Counter=1
-- Less than or greater than symbol is not allowed in description to -----removing that from example and only kept "="
While @Counter=@TotalCount
Begin
Select @EmpId=EmpId,@EmpName=EmpName,@Salary=Salary from #Emp where Rn=@Counter
Print Concat(@EmpId,' '+ @EmpName +' ' , @Salary)

Set @Counter+=1
End

Drop table #Emp

Тэги:

#SQL_Interview #SQL_Basics #SQL #SQL_Loop #While_loop #Loop
Ссылки и html тэги не поддерживаются


Комментарии:

Hasan Mougharbel
Hasan Mougharbel - 05.10.2022 19:31

Hey there,
God bless your efforts.
I am a newbie sql learner with a simple enquiry.
Why i cannot set constraints or indexes for CTE's?
Thanks .

Ответить