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?
Just a quick note, if you are using SQL Server (2008 and above), the examples that have:
Would be better served with
The Count will have to touch every single row in the table, the
EXISTS
only needs to touch the first one.Lightweight, without having to make extra tables, if you have an integer
ID
on the tableI agree with the previous post that set-based operations will typically perform better, but if you do need to iterate over the rows here's the approach I would take:
Select the next unused record from the table and repeat the process
This is how I do it:
No Cursors, no temporary tables, no extra columns. The USERID column must be a unique integer, as most Primary Keys are.
Another approach without having to change your schema or using temp tables:
This will work in SQL SERVER 2012 version.