I have the following TSQL codes:
-- 1. define a cursor DECLARE c_Temp CURSOR FOR SELECT name FROM employees; DECLARE @name varchar(100); -- 2. open it OPEN c_Temp; -- 3. first fetch FETCH NEXT FROM c_Temp INTO @name; WHILE @@FETCH_STATUS = 0 BEGIN print @name; FETCH NEXT FROM c_Temp INTO @name; -- fetch again in a loop END -- 4. close it ....
I use the name value only in a loop block. Here I have to
- define a cursor variable,
- open it,
- fetch twice and
- close it.
In PL/SQL, the loop can be like this:
FOR rRec IN (SELECT name FROM employees) LOOP DBMS_OUTPUT.put_line(rRec.name); END LOOP;
It is much simpler than my TSQL codes. No need to define a cursor. It is created dynamically which is accessible within a loop block (much like C# for loop). Not sure if there something similar like this in TSQL?
Cursors are evil in Sql Server as they can really degrade performance – my favoured approach is to use a Table Variable (>= Sql Server 2005) with an auto inc ID column:
It looks pretty long winded however works in any situation and should be far more lightweight than a cursor