How to change cursor's select statement by some condition? - sql

Does any body know how to set different select statement for the same cursor? I need somethink like this.
DECLARE Temp_Cursor CURSOR FOR
IF(#TempVar = 1)
BEGIN
SELECT CustomerId FROM Customers
END
ELSE IF(#TempVar = 2)
BEGIN
SELECT OrderId FROM Orders
END
OPEN Temp_Cursor;
FETCH NEXT FROM TempCursor INTO #TempObjectId
WHILE ##FETCH_STATUS = 0
BEGIN
.... etc
I have found solution: DECLARE #Temp_Cursor CURSOR
IF(#TempVar = 1)
BEGIN
SET #Temp_Cursor = CURSOR FOR
SELECT CustomerId FROM Customers
END
ELSE IF(#TempVar = 2)
BEGIN
SET #Temp_Cursor = CURSOR FOR
SELECT OrderId FROM Orders
END
OPEN #Temp_Cursor;
FETCH NEXT FROM #TempCursor INTO #TempObjectId
WHILE ##FETCH_STATUS = 0
BEGIN

Put the IF outside and do two different cursors, one for each situation.
Like this:
IF(#TempVar = 1)
BEGIN
DECLARE Temp_Cursor CURSOR FOR
SELECT CustomerId FROM Customers
OPEN Temp_Cursor;
FETCH NEXT FROM TempCursor INTO #TempObjectId
WHILE ##FETCH_STATUS = 0
BEGIN
....
END
ELSE IF(#TempVar = 2)
BEGIN
DECLARE Temp_Cursor CURSOR FOR
SELECT OrderId FROM Orders
OPEN Temp_Cursor;
FETCH NEXT FROM TempCursor INTO #TempObjectId
WHILE ##FETCH_STATUS = 0
BEGIN
....
END
Another possibility is to use Dynamic SQL.

The complete query should be dynamic. That means the execution plan will come out at run time.
Example
Declare #SelectStatement Varchar(50)
Declare #SQL Varchar(50)
IF(#TempVar = 1)
BEGIN
Set #SelectStatement = SELECT CustomerId FROM Customers
END
ELSE IF(#TempVar = 2)
BEGIN
Set #SelectStatement = SELECT OrderId FROM Orders
END
Set #SQL = 'DECLARE Temp_Cursor CURSOR FOR
OPEN Temp_Cursor;
FETCH NEXT FROM TempCursor INTO ' + #TempObjectId +
'WHILE ##FETCH_STATUS = 0
BEGIN '

Related

How do I loop through the results of a SELECT statement sql and use the result for stored procedure?

I want to use the result of a select query into a stored procedure by using cursor but it doesn't work.
Here is my code:
DECLARE #NumberPhone varchar(50)
DECLARE CUR CURSOR STATIC FOR
SELECT MobilePhone
FROM info_client
OPEN CUR
FETCH NEXT FROM CUR INTO #NumberPhone
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #return_value int, #idCli int, #sCode varchar(2)
EXEC #return_value = StoredP_Test
#sLignePhone = #NumberPhone,
#sIMEI ='00000000000000000',
#idCli = #idCli OUTPUT,
#sCode = #sCode OUTPUT
SELECT #idCli as N'#idCli',
#sCode as N'#sCode'
FETCH NEXT FROM CUR INTO #NumberPhone
SELECT 'Return Value' = #return_value
END
CLOSE CUR
DEALLOCATE CUR
This code duplicate the same result as the number of line of the select query.
Your code has an initial fetch of
FETCH NEXT FROM CUR INTO #NumberPhone
Your code has a fetch next inside the loop
FETCH NEXT FROM CUR INTO #sLigneAssValue
Didn't you want to fetch next into the #NumberPhone variable?
The #NumberPhone variable will never change.

Function with a cursor, cant find the error

I'm not quite sure what I typed in that was wrong. This is the error I receive from my SQL code:
Msg 102, Level 15, State 1, Procedure GradeAverage, Line 22
Incorrect syntax near 'myCursor'.
Function:
CREATE FUNCTION GradeAverage
(#StudentID as varchar(20))
RETURNS int
AS
BEGIN
DECLARE #Final int
DECLARE #Grade int
DECLARE #Total int= 0
DECLARE #Count int = 0
DECLARE myCursor CURSOR FOR
SELECT FinalGrade
FROM CourseEnrollment
WHERE StudentId = #StudentID AND FinalGrade IS NOT NULL
OPEN myCursor;
FETCH NEXT FROM myCursor INTO #Grade
WHILE ##FETCH_STATUS = 0
BEGIN
SET #Total = #Grade + #Total;
SET #Count = #Count +1;
FETCH NEXT FROM myCursor INTO #Grade
END
SET #Final = (#Total/#Count);
CLOSE myCursor
DEALLOCATE myCursor
RETURNS #Final
The first problem is that RETURNS declares the return type of the function as in RETURNS int, but to actually specify the return value, you need to use RETURN (no S):
The second problem is that each BEGIN in your function definition must be matched with an END, including the BEGIN/END which surrounds your entire function body.
Finally, for the sake of readability, I suggest you adopt some more standard formatting conventions. It should look like this:
CREATE FUNCTION GradeAverage (#StudentID as varchar(20)) RETURNS int
AS
BEGIN
DECLARE #Final int;
DECLARE #Grade int;
DECLARE #Total int= 0;
DECLARE #Count int = 0;
DECLARE myCursor CURSOR FOR
SELECT FinalGrade
FROM CourseEnrollment
WHERE StudentId = #StudentID AND FinalGrade IS NOT NULL;
OPEN myCursor;
FETCH NEXT FROM myCursor INTO #Grade;
WHILE ##FETCH_STATUS = 0
BEGIN
SET #Total = #Grade + #Total;
SET #Count = #Count +1;
FETCH NEXT FROM myCursor INTO #Grade;
END
SET #Final = (#Total/#Count);
CLOSE myCursor;
DEALLOCATE myCursor;
RETURN #Final;
END

Return one table from cursor

Please see the code below:
DECLARE #ID int
DECLARE #errorflag int
DECLARE Warning_Cursor CURSOR FOR
SELECT TOP 3 ID FROM Warnings
SET #errorflag = #errorflag + ##Error
OPEN Warning_cursor
SET #errorflag = #errorflag + ##Error
FETCH NEXT FROM Warning_cursor INTO #ID
WHILE ##FETCH_STATUS = 0
begin
SELECT #ID
FETCH NEXT FROM Warning_cursor INTO #ID
END
CLOSE Warning_cursor
DEALLOCATE Warning_cursor
The cursor returns three tables with one row each. How can I return one table with three rows?
Why don't you just do,
SELECT TOP 3 ID FROM Warnings
More generally, if you are using a cursor, you are probably doing it wrong.
If you really have to use a cursor for some reason that is not part of the question. You could do
DECLARE #Id int;
DECLARE #Ids TABLE (Id Int);
DECLARE Warning_Cursor CURSOR FOR SELECT TOP 3 ID FROM Warnings;
OPEN Warning_cursor;
FETCH NEXT FROM Warning_cursor INTO #Id;
WHILE ##FETCH_STATUS = 0 BEGIN
INSERT #Ids SELECT #Id;
FETCH NEXT FROM Warning_cursor INTO #Id;
END
CLOSE Warning_cursor;
DEALLOCATE Warning_cursor;
SELECT Id FROM #Ids;
The answer was to create a temporary table as follows:
DECLARE #ID int
DECLARE #errorflag int
DECLARE #CONCATRESULT TABLE (ID INT)
DECLARE Warning_Cursor CURSOR FOR
SELECT TOP 3 ID FROM Warnings
SET #errorflag = #errorflag + ##Error
OPEN Warning_cursor
SET #errorflag = #errorflag + ##Error
FETCH NEXT FROM Warning_cursor INTO #ID
WHILE ##FETCH_STATUS = 0
begin
INSERT into #CONCATRESULT (ID) VALUES (#ID)
FETCH NEXT FROM Warning_cursor INTO #ID
END
CLOSE Warning_cursor
DEALLOCATE Warning_cursor
select id from #CONCATRESULT

Get Multiple Values in SQL Server Cursor

I have a cursor containing several columns from the row it brings back that I would like to process at once. I notice most of the examples I've seeing on how to use cursors show them assigning a particular column from the cursor to a scalar value one at a time, then moving to the next row,
e.g.
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #name
WHILE ##FETCH_STATUS = 0
BEGIN
--Do Stuff with #name scalar value, then get next row from cursor
FETCH NEXT FROM db_cursor INTO #name
END
What I want to know is if it's possible to do something like the following:
OPEN db_cursor
FETCH NEXT FROM db_cursor;
WHILE ##FETCH_STATUS = 0
BEGIN
SET #myName = db_cursor.name;
SET #myAge = db_cursor.age;
SET #myFavoriteColor = db_cursor.favoriteColor;
--Do stuff with scalar values
FETCH NEXT FROM db_cursor;
END
Help is always appreciated.
This should work:
DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table;
DECLARE #myName VARCHAR(256);
DECLARE #myAge INT;
DECLARE #myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO #myName, #myAge, #myFavoriteColor;
WHILE ##FETCH_STATUS = 0
BEGIN
--Do stuff with scalar values
FETCH NEXT FROM db_cursor INTO #myName, #myAge, #myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
Do not use ##fetch_status - this will return status from the last cursor in the current connection. Use the example below:
declare #sqCur cursor;
declare #data varchar(1000);
declare #i int = 0, #lastNum int, #rowNum int;
set #sqCur = cursor local static read_only for
select
row_number() over (order by(select null)) as RowNum
,Data -- you fields
from YourIntTable
open #cur
begin try
fetch last from #cur into #lastNum, #data
fetch absolute 1 from #cur into #rowNum, #data --start from the beginning and get first value
while #i < #lastNum
begin
set #i += 1
--Do your job here
print #data
fetch next from #cur into #rowNum, #data
end
end try
begin catch
close #cur --|
deallocate #cur --|-remove this 3 lines if you do not throw
;throw --|
end catch
close #cur
deallocate #cur

Cursor inside cursor

Main problem is about changing the index of rows to 1,2,3.. where contact-id and type is the same. but all columns can contain exactly the same data because of some ex-employee messed up and update all rows by contact-id and type. somehow there are rows that aren't messed but index rows are same. It is total chaos.
I tried to use an inner cursor with the variables coming from the outer cursor.
But It seems that its stuck in the inner cursor.
A part of the query looks like this:
Fetch NEXT FROM OUTER_CURSOR INTO #CONTACT_ID, #TYPE
While (##FETCH_STATUS <> -1)
BEGIN
IF (##FETCH_STATUS <> -2)
DECLARE INNER_CURSOR Cursor
FOR
SELECT * FROM CONTACTS
where CONTACT_ID = #CONTACT_ID
and TYPE = #TYPE
Open INNER_CURSOR
Fetch NEXT FROM INNER_CURSOR
While (##FETCH_STATUS <> -1)
BEGIN
IF (##FETCH_STATUS <> -2)
What can be the problem? Is ##FETCH_STATUS ambiguous or something?
EDIT: everything looks fine if i don't use this code inside inner cursor:
UPDATE CONTACTS
SET INDEX_NO = #COUNTER
where current of INNER_CURSOR
EDIT: here is the big picture:
BEGIN TRAN
DECLARE #CONTACT_ID VARCHAR(15)
DECLARE #TYPE VARCHAR(15)
DECLARE #INDEX_NO SMALLINT
DECLARE #COUNTER SMALLINT
DECLARE #FETCH_STATUS INT
DECLARE OUTER_CURSOR CURSOR
FOR
SELECT CONTACT_ID, TYPE, INDEX_NO FROM CONTACTS
WHERE
CONTACT_ID IN (SELECT CONTACT_ID FROM dbo.CONTACTS
WHERE CONTACT_ID IN(...)
GROUP BY CONTACT_ID, TYPE, INDEX_NO
HAVING COUNT(*) > 1
OPEN OUTER_CURSOR
FETCH NEXT FROM OUTER_CURSOR INTO #CONTACT_ID, #TYPE, #INDEX_NO
WHILE (##FETCH_STATUS <> -1)
BEGIN
IF (##FETCH_STATUS <> -2)
SET #COUNTER = 1
DECLARE INNER_CURSOR CURSOR
FOR
SELECT * FROM CONTACTS
WHERE CONTACT_ID = #CONTACT_ID
AND TYPE = #TYPE
FOR UPDATE
OPEN INNER_CURSOR
FETCH NEXT FROM INNER_CURSOR
WHILE (##FETCH_STATUS <> -1)
BEGIN
IF (##FETCH_STATUS <> -2)
UPDATE CONTACTS
SET INDEX_NO = #COUNTER
WHERE CURRENT OF INNER_CURSOR
SET #COUNTER = #COUNTER + 1
FETCH NEXT FROM INNER_CURSOR
END
CLOSE INNER_CURSOR
DEALLOCATE INNER_CURSOR
FETCH NEXT FROM OUTER_CURSOR INTO #CONTACT_ID, #TYPE, #INDEX_NO
END
CLOSE OUTER_CURSOR
DEALLOCATE OUTER_CURSOR
COMMIT TRAN
You have a variety of problems. First, why are you using your specific ##FETCH_STATUS values? It should just be ##FETCH_STATUS = 0.
Second, you are not selecting your inner Cursor into anything. And I cannot think of any circumstance where you would select all fields in this way - spell them out!
Here's a sample to go by. Folder has a primary key of "ClientID" that is also a foreign key for Attend. I'm just printing all of the Attend UIDs, broken down by Folder ClientID:
Declare #ClientID int;
Declare #UID int;
DECLARE Cur1 CURSOR FOR
SELECT ClientID From Folder;
OPEN Cur1
FETCH NEXT FROM Cur1 INTO #ClientID;
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT 'Processing ClientID: ' + Cast(#ClientID as Varchar);
DECLARE Cur2 CURSOR FOR
SELECT UID FROM Attend Where ClientID=#ClientID;
OPEN Cur2;
FETCH NEXT FROM Cur2 INTO #UID;
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT 'Found UID: ' + Cast(#UID as Varchar);
FETCH NEXT FROM Cur2 INTO #UID;
END;
CLOSE Cur2;
DEALLOCATE Cur2;
FETCH NEXT FROM Cur1 INTO #ClientID;
END;
PRINT 'DONE';
CLOSE Cur1;
DEALLOCATE Cur1;
Finally, are you SURE you want to be doing something like this in a stored procedure? It is very easy to abuse stored procedures and often reflects problems in characterizing your problem. The sample I gave, for example, could be far more easily accomplished using standard select calls.
You could also sidestep nested cursor issues, general cursor issues, and global variable issues by avoiding the cursors entirely.
declare #rowid int
declare #rowid2 int
declare #id int
declare #type varchar(10)
declare #rows int
declare #rows2 int
declare #outer table (rowid int identity(1,1), id int, type varchar(100))
declare #inner table (rowid int identity(1,1), clientid int, whatever int)
insert into #outer (id, type)
Select id, type from sometable
select #rows = count(1) from #outer
while (#rows > 0)
Begin
select top 1 #rowid = rowid, #id = id, #type = type
from #outer
insert into #innner (clientid, whatever )
select clientid whatever from contacts where contactid = #id
select #rows2 = count(1) from #inner
while (#rows2 > 0)
Begin
select top 1 /* stuff you want into some variables */
/* Other statements you want to execute */
delete from #inner where rowid = #rowid2
select #rows2 = count(1) from #inner
End
delete from #outer where rowid = #rowid
select #rows = count(1) from #outer
End
Do you do any more fetches? You should show those as well. You're only showing us half the code.
It should look like:
FETCH NEXT FROM #Outer INTO ...
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #Inner...
OPEN #Inner
FETCH NEXT FROM #Inner INTO ...
WHILE ##FETCH_STATUS = 0
BEGIN
...
FETCH NEXT FROM #Inner INTO ...
END
CLOSE #Inner
DEALLOCATE #Inner
FETCH NEXT FROM #Outer INTO ...
END
CLOSE #Outer
DEALLOCATE #Outer
Also, make sure you do not name the cursors the same... and any code (check your triggers) that gets called does not use a cursor that is named the same. I've seen odd behavior from people using 'theCursor' in multiple layers of the stack.
This smells of something that should be done with a JOIN instead. Can you share the larger problem with us?
Hey, I should be able to get this down to a single statement, but I haven't had time to play with it further yet today and may not get to. In the mean-time, know that you should be able to edit the query for your inner cursor to create the row numbers as part of the query using the ROW_NUMBER() function. From there, you can fold the inner cursor into the outer by doing an INNER JOIN on it (you can join on a sub query). Finally, any SELECT statement can be converted to an UPDATE using this method:
UPDATE [YourTable/Alias]
SET [Column] = q.Value
FROM
(
... complicate select query here ...
) q
Where [YourTable/Alias] is a table or alias used in the select query.
I had the same problem,
what you have to do is declare the second cursor as:
DECLARE [second_cursor] Cursor LOCAL For
You see"CURSOR LOCAL FOR" instead of "CURSOR FOR"
I don't fully understand what was the problem with the "update current of cursor" but it is solved by using the fetch statement twice for the inner cursor:
FETCH NEXT FROM INNER_CURSOR
WHILE (##FETCH_STATUS <> -1)
BEGIN
UPDATE CONTACTS
SET INDEX_NO = #COUNTER
WHERE CURRENT OF INNER_CURSOR
SET #COUNTER = #COUNTER + 1
FETCH NEXT FROM INNER_CURSOR
FETCH NEXT FROM INNER_CURSOR
END