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 2000 Forums
 Transact-SQL (2000)
 While Loops

Author  Topic 

davidfb
Starting Member

8 Posts

Posted - 2002-09-11 : 08:46:21
Can someone show me an example of using a while loop instead of using cursors?

I´ve read one example here in the site, but i didn´t understand that at all.. It would be very useful!

Thanks in advance,

David.

Page47
Master Smack Fu Yak Hacker

2878 Posts

Posted - 2002-09-11 : 08:52:20
A cursor is a mechanism to work with one row or a small block of rows at a time. A while loop is a flow-control construct. Apples & Oranges....

If you have some logic implemented with a cursor, and you'd like to get some help with getting rid of the cursor, post your code and applicable DDL.

Jay White
{0}
Go to Top of Page

nr
SQLTeam MVY

12543 Posts

Posted - 2002-09-11 : 09:21:55
You can always replace a cursor by

create table #a (id int identity, ...)
insert #a (...)
select ... -- select you would have had in the cursor

declare @id int, @maxid int
select @id = 0 , @maxid = max(id) from #a
while @id < @Maxid
begin
select @id = min(id) from #a where id > @id

you can get all the fields from thye row in #a by use @id here

end

If you just do this it's not much better and is probably slower than the cursor but you can do processing on the whole #a table to do things a lot more quickly even if you do process row by row in the final step.
You can usually process in batches in #a though.



==========================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page
   

- Advertisement -