sql server - Is there a way to loop through a table variable in TSQL without using a cursor? -


let's have following simple table variable:

declare @databases table (     databaseid    int,     name        varchar(15),        server      varchar(15) ) -- insert bunch rows @databases 

is declaring , using cursor option if wanted iterate through rows? there way?

first of should absolutely sure need iterate through each row - set based operations perform faster in every case can think of , use simpler code.

depending on data may possible loop using select statements shown below:

declare @id int  while (select count(*) atable processed = 0) > 0 begin     select top 1 @id = id atable processed = 0      --do processing here      update atable set processed = 1 id = @id   end 

another alternative use temporary table:

select *   #temp   atable  declare @id int  while (select count(*) #temp) > 0 begin      select top 1 @id = id #temp      --do processing here      delete #temp id = @id  end 

the option should choose depends on structure , volume of data.

note: if using sql server better served using:

while exists(select * #temp) 

using count have touch every single row in table, exists needs touch first 1 (see josef's answer below).


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -