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?
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
Several options:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With