Skip to content
Advertisement

To convert the WHILE loop query into FOR loop query

This is the table created and inserted values into it in SQL server

create table Country (
id int, countryname varchar(25)
)
insert into country (id, countryname) 
values (1,'India'), (2,'Austria'), (3,'Sri Lanka'), (4,'Mongolia'), (5,'Russia')

And using WHILE loop, I achieved the below query in SQL Server.

declare @id int, @countryname varchar(30), @maxid int
select @id=min(id), @maxid=max(id)
from country
while(@id is not null and @id<=@maxid)
begin
select @countryname=`countryname`    
from Country where id=@id
print convert`(varchar,@id)`+'. country name is '+ @countryname
set @id=@id+1
end

Now I want the same above result with the usage of FOR loop, I know in SQL server FOR loop is not used, but with WHILE loop we can simulate the FOR loop in SQL server.

Can anyone help me with this?

Advertisement

Answer

Use a query, not a loop with print:

In SQL we always try to work on sets at once, and not use while loops or cursors.

select
    concat(convert(varchar(12), @id), '. country name is ', countryname)
from Country
order by id
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement