Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A cursor with the name 'cursor_name' does not exist

I have a code the uses nested cursors. When I parse it, SQL studio tells me "Command(s) completed successfully," but whenever I execute, I get a bunch of repeated "A cursor with the name 'cursor_stats' does not exist." The error message displays for every line cursor_stats is mentioned in, then repeats many times. Any idea what my problem is?

DECLARE @dc_grp AS VARCHAR(50)
DECLARE @reqt_id AS INT

DECLARE cursor_pairs CURSOR FOR
 SELECT DISTINCT dc.dc_grp, dcx.reqt_id
 FROM DC_GRP dc INNER JOIN
      DC_GRPX dcx ON dc.dc_grp = dcx.dc_grp INNER JOIN
      REQT req ON dcx.reqt_id = req.reqt_id
WHERE dc.calc_stddev = 1 AND req.v_a = 'V' AND dcx.stddev_last_update != CONVERT(datetime, Convert(int, GetDate()))
ORDER BY dc.dc_grp, dcx.reqt_id

--------------------------------------
DECLARE @vavg AS FLOAT
DECLARE @vstddev AS FLOAT

DECLARE cursor_stats CURSOR FOR
 SELECT AVG(r.[var]), STDEV(r.[var])
 FROM RESULTS r INNER JOIN
      INSTANCE i ON r.inst_id = i.inst_id
 WHERE i.dc_grp = @dc_grp AND r.reqt_id = @reqt_id AND r.[var] != 0 AND r.inst_id IN 
          (
          SELECT TOP 100 inst_id
          FROM RESULTS
          WHERE reqt_id = @reqt_id
          ORDER BY inst_id DESC
          )

---------------------------------------

OPEN cursor_pairs
   FETCH NEXT FROM cursor_pairs INTO @dc_grp, @reqt_id
   WHILE @@FETCH_STATUS = 0
   BEGIN
     OPEN cursor_stats
        FETCH NEXT FROM cursor_stats INTO @vavg, @vstddev
        WHILE @@FETCH_STATUS = 0
        BEGIN
          PRINT @dc_grp + ' ' + @reqt_id + ' ' + @vavg + ' ' + @vstddev
        FETCH NEXT FROM cursor_stats INTO @vavg, @vstddev
        END
     CLOSE cursor_stats
     DEALLOCATE cursor_stats
   FETCH NEXT FROM cursor_pairs INTO @dc_grp, @reqt_id
   END
CLOSE cursor_pairs
DEALLOCATE cursor_pairs
like image 853
Kevin Kesicki Avatar asked Jul 31 '13 13:07

Kevin Kesicki


1 Answers

You should NOT DEALLOCATE cursor_stats inside the loop.

http://msdn.microsoft.com/en-us/library/ms188782.aspx

Only do it after ALL processing is finished

like image 166
Germann Arlington Avatar answered Sep 25 '22 16:09

Germann Arlington