Convert PLSQL Cursor FOR Loop Syntax to TSQL - tsql

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?

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

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

Related

While loop in cursor not working properly

I tried storing the result in a varable and use coalece.
But it is not working.
do
$$
declare
v_deptno numeric := 10;
stored_empno numeric;
curempno cursor is select empno from emp e where e.deptno = v_deptno;
recempno record;
begin
open curempno;
fetch curempno
into recempno;
while found
loop
fetch curempno into recempno;
stored_empno:=recProdTest.empno;
raise info 'empno = %',coalesce(recProdTest.empno, stored_empno);
end loop;
close curempno;
end $$ language plpgsql;
Please help me.
Thanks.
Your program logic is wrong, and that won't work in Oracle either.
How many FETCH statements are executed before the first RAISE? Exactly, two: one before the loop, one in the loop.
So you are skipping the first result. The final NULL is because you don't check FOUND between FETCH and RAISE, so you report the empty result you get because the cursor is done.
Try a loop like this:
OPEN curempno;
LOOP
FETCH curempno INTO recempno;
EXIT WHEN NOT FOUND;
RAISE INFO 'empno = %', recempno.empno;
END LOOP;

Trigger after update: How to execute query for every row updated

I wrote trigger to execute a query after the update of the column (retard) in my table, but sometimes there are many rows updated how to solve that?
CREATE OR ALTER TRIGGER notifRetard
ON Taches
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE #value INT
IF UPDATE(retard)
-- How to make this for every row updated???
SELECT
#value = inserted.retard
FROM
inserted;
IF #value = 1
-- run SQL query
END
The solution if someone else need it is to use CURSOR.
CREATE or alter TRIGGER notifRetard
ON Taches
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF UPDATE(retard)
begin
DECLARE #RefTache varchar(50),#RefPhase numeric(4,0),#IDprojet varchar(50),#IDressource varchar(50) #retard bit;
DECLARE TrigTempUpdate_Cursor CURSOR FOR
SELECt RefTache,RefPhase,IDprojet,IDressource,retard
FROM
inserted;
begin
OPEN TrigTempUpdate_Cursor;
FETCH NEXT FROM TrigTempUpdate_Cursor INTO #RefTache, #RefPhase,#IDprojet,#IDressource,#retard
WHILE ##FETCH_STATUS = 0
BEGIN
if #retard=1
--DO QUERY HERE
FETCH NEXT FROM TrigTempUpdate_Cursor INTO #RefTache, #RefPhase,#IDprojet,#IDressource,#retard
END;
end;
CLOSE TrigTempUpdate_Cursor;
DEALLOCATE TrigTempUpdate_Cursor;
end;
end;

How to use a cursor inside a loop in a PostgreSQL script

I want to make a script for a PostgreSQL database which reads a table and prints its content. I have used the following code
declare myCursor cursor for
select col1, col2 from tab1;
begin
loop
DBMS_OUTPUT.PUT_LINE(myCursor .col1+" "+myCursor.col2);
end loop;
end;
But it doesn't work.
Eventually I have found out:
do $$
declare myCursor cursor for
select col1, col2 from tab1;
begin
for myIterator in myCursor loop
raise notice '% %', myIterator.col1, myIterator.col2;
end loop;
end $$;

SQLCODE=-501 SQLSTATE=24501 with Cursor

I have written a stored procedure as
CREATE OR REPLACE PROC1()
DECLARE VAR1 INT;
DECLARE VAR2 INT;
DECLARE TEXT VARCHAR(1000);
DECLARE exitcode INTEGER DEFAULT 0;
DECLARE SQLCODE INTEGER DEFAULT 0;
DECLARE CUR1 CURSOR WITH HOLD for STMT1 ;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET exitcode = 1;
SET TEXT= (-----);
PREPARE STMT1 FROM TEXT;
open cur1;
fetch from cur1 into var1,var2;
while(sqlcode =0)
do
--
--
CALL SYSPROC.ADMIN_CMD('REORG TABLE emp1 ');
set exit code = 0;
fetch from cur1 into var1,var2;
IF (exitcode = 1)
THEN
LEAVE wloop;
END IF;
end while;
close cur1;
My question is even I declared my cursor as WITH HOLD option, after the first fetch the cursor is closing & throwing -501 error.If i remove the REORG statement from the loop. Then cursor is working normally,fetching all the rows. Can some one tel me the way to keep my cursor to be open even If i use the REORG statement inside the loop.
Thanks in advance

TSQL Cursor Infinite Loop without TOP xxx in SELECT Statement

I have a curious problem with an infinite loop in a TSQL cursor. The cursor loops infinitely when I do not add TOP 300 to the defining select statement of the cursor. The following is an example of the code: Any assistance to this issue is much appreciated.
DECLARE #Done BIT
SET #Done = 0
DECLARE cursOut CURSOR LOCAL FAST_FORWARD
FOR
SELECT
--TOP 300
FirstName FirstName
,LastName LastName
,MiddleName MiddleName
,Email Email
,Address1 Address1
,Address2 Address2
,City City
,[State] [State]
FROM StagedUsers
OPEN cursOut;
WHILE (#Done = 0)
BEGIN
--Fetch next row
FETCH NEXT
FROM cursOut
INTO ,#v_FirstName
,#v_LastName
,#v_MiddleName
,#v_Email
,#v_Address1
,#v_Address2
,#v_City
,#v_State
IF (##FETCH_STATUS <> 0)
BEGIN
SET #Done = 1
BREAK
END
--if #batch = 0
BEGIN TRANSACTION
--process statements
--updates or insert statements
--Commit transaction
COMMIT TRANSACTION
--End While
END
--CleanUp:
CLOSE cursOut
DEALLOCATE cursOut
Thanks,
Renegrin
First I think you do not need transaction here, I presume it is only one statement executed, so remove transaction from code.
Second do it without #done flag, it is confusing (it is probably not problem here).
DECLARE #v_FirstName VARCHAR(500),#v_LastName VARCHAR(500),#v_MiddleName VARCHAR(500),#v_Email VARCHAR(500),#v_Address1 VARCHAR(500),#v_Address2 VARCHAR(500),#v_City VARCHAR(500),#v_State VARCHAR(500)
DECLARE cursOut CURSOR FAST_FORWARD FOR
SELECT FirstName FirstName,LastName LastName,MiddleName MiddleName,Email Email,Address1 Address1,Address2 Address2,City City,[State] [State]
FROM StagedUsers
OPEN cursOut;
FETCH NEXT FROM cursOut INTO #v_FirstName,#v_LastName,#v_MiddleName,#v_Email,#v_Address1,#v_Address2,#v_City,#v_State
declare #i int = 1
WHILE ##FETCH_STATUS = 0
BEGIN
print cast(#i as varchar(10))
--> statement here
FETCH NEXT FROM cursOut INTO #v_FirstName,#v_LastName,#v_MiddleName,#v_Email,#v_Address1,#v_Address2,#v_City,#v_State
set #i = #i + 1
END
CLOSE cursOut
DEALLOCATE cursOut
Do you want to update current row where cursor point? If so, there is way to do it.
Is there any indexes on table? Can you post an update query?