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?
I prefer using the Offset Fetch if you have a unique ID you can sort your table by:
This way I don't need to add fields to the table or use a window function.
Here is how I would do it:
[Edit] Because I probably skipped the word "variable" when I first time read the question, here is an updated response...
I'm going to provide the set-based solution.
This is far faster than any looping techique and is easier to write and maintain.
Step1: Below select statement creates a temp table with unique row number for each record.
Step2:Declare required variables
Step3: Take total rows count from temp table
Step4: Loop temp table based on unique row number create in temp
This approach only requires one variable and does not delete any rows from @databases. I know there are a lot of answers here, but I don't see one that uses MIN to get your next ID like this.
You can use a while loop: