Let's say I have the following simple table variable:
declare @databases table
(
DatabaseID int,
Name varchar(15),
Server varchar(15)
)
-- insert a bunch rows into @databases
Is declaring and using a cursor my only option if I wanted to iterate through the rows? Is there another way?
Here's my solution, which makes use of an infinite loop, the
BREAK
statement, and the@@ROWCOUNT
function. No cursors or temporary table are necessary, and I only need to write one query to get the next row in the@databases
table:Select @pk = @pk + 1 would be better: SET @pk += @pk. Avoid using SELECT if you are not referencing tables are are just assigning values.
Define your temp table like this -
Then do this -
It's possible to use a cursor to do this:
create function [dbo].f_teste_loop returns @tabela table ( cod int, nome varchar(10) ) as begin
end
create procedure [dbo].[sp_teste_loop] as begin
end
First of all you should be absolutely sure you need to iterate through each row - set based operations will perform faster in every case I can think of and will normally use simpler code.
Depending on your data it may be possible to loop just using select statements as shown below:
Another alternative is to use a temporary table:
The option you should choose really depends on the structure and volume of your data.
Note: If you are using SQL Server you would be better served using:
Using
COUNT
will have to touch every single row in the table, theEXISTS
only needs to touch the first one (see Josef's answer below).If you have no choice than to go row by row creating a FAST_FORWARD cursor. It will be as fast as building up a while loop and much easier to maintain over the long haul.
FAST_FORWARD Specifies a FORWARD_ONLY, READ_ONLY cursor with performance optimizations enabled. FAST_FORWARD cannot be specified if SCROLL or FOR_UPDATE is also specified.