Reputation: 5358
what are the alternatives to using cursors in sql server. i already know a trick which involves using the Row_Number() function which numbers the rows then i can loop over them one by one. any other ideas?
Upvotes: 4
Views: 5653
Reputation: 146469
Several options:
Upvotes: 2
Reputation: 4533
When I don't want to complicate things with SQL cursors I often populate temporary tables or table variables, then do a while loop to go through them.
For example:
declare @someresults table (
id int,
somevalue varchar(10)
)
insert into @someresults
select
id,
somevalue
from
whatevertable
declare @currentid int
declare @currentvalue varchar(10)
while exists(select 1 from @someresults)
begin
select top 1 @currentid = id, @currentvalue = somevalue from @someresults
--work with those values here
delete from @someresults where id = @currentid
end
Upvotes: 10