views:

33

answers:

3

I have some PLSQL code which loops through some logic:

 FOR I in cur1
 LOOP

    SELECT value1, value2
    FROM db1..table1 t1

 END LOOP;

Can anyone explain to me the syntax for doing this in TSQL?

A: 

This is a generic loop in a standar TSQL Cursor. But try to avoid Cursors when possible. They Have very bad performance.

DECLARE @somevariable VARIABLE_TYPE_HERE
DECLARE @sampleCursor CURSOR

SET @sampleCursor = CURSOR FOR
SELECT somefield... from bla bla bla...

OPEN @sampleCursor 
FETCH NEXT
FROM @sampleCursor INTO @somevariable 
WHILE @@FETCH_STATUS = 0
BEGIN

PRINT @somevariable 

FETCH NEXT
FROM @sampleCursor INTO @somevariable 

END
CLOSE @sampleCursor 
DEALLOCATE @sampleCursor 
Jonathan
Coming from an ORacle world here cursors are much more common, the poster is probaly used to using them. It is very important to avoid them in SQL Server.
HLGEM
A: 

There is no FOR in T-SQL. An example with WHILE:

DECLARE Employee_Cursor CURSOR FOR
SELECT EmployeeID, Title 
FROM AdventureWorks2008R2.HumanResources.Employee

OPEN Employee_Cursor;

FETCH NEXT FROM Employee_Cursor;

WHILE @@FETCH_STATUS = 0
BEGIN
   FETCH NEXT FROM Employee_Cursor;
END;

CLOSE Employee_Cursor;

DEALLOCATE Employee_Cursor;

For more information: http://msdn.microsoft.com/en-us/library/ms178642.aspx

mcabral
A: 

JUst so you cn explore better ways to do things in SQL Server:

http://wiki.lessthandot.com/index.php/Cursors_and_How_to_Avoid_Them

HLGEM