Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 can this ever be useful

Author  Topic 

joe8079
Posting Yak Master

127 Posts

Posted - 2011-12-23 : 18:35:45

I got bored at work and put together a query that loops through a table and prints out one row at a time where the result set is only 31 rows and I was wondering how can something like this be useful? The query is from the northwind database. I'm just curious to see if something like this could ever be useful because I hear people talk about while loops and cursors in T-SQL, but have not found any reason to ever use them.





declare @counter int
set @counter = 1
declare @max int
select @max = max(aa.rownum) from (select row_number() over(order by lastname )rownum, title from employees where firstname like 'M%'
) as aa

while @counter <= @max
begin



select aa.rownum, aa.title, aa.firstname, aa.lastname


from

(select row_number() over(order by lastname)rownum, title, firstname, lastname
from employees where firstname like 'M%') as aa
where @counter = aa.rownum

set @counter = @counter + 1
end

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-12-23 : 23:17:55
whilst what you've done can be used for cursor or loop based logic, in most cases its possible to replace this with a set based solution which would be much more performing.

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -