This is the table created and inserted values into it in SQL server
x
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 intselect @id=min(id), @maxid=max(id)from countrywhile(@id is not null and @id<=@maxid)beginselect @countryname=`countryname` from Country where id=@idprint convert`(varchar,@id)`+'. country name is '+ @countrynameset @id=@id+1endNow 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 Countryorder by id