名称为“cursor_name”的游标不存在

时间:2013-07-31 13:39:43

标签: sql cursor

我有一个使用嵌套游标的代码。当我解析它时,SQL工作室告诉我“命令已成功完成”,但每当我执行时,我都会得到一堆重复的“一个名为'cursor_stats'的游标不存在。”显示每行提供的错误消息cursor_stats,然后重复多次。知道我的问题是什么吗?

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

1 个答案:

答案 0 :(得分:8)

你不应该在循环中DEALLOCATE cursor_stats

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

仅在所有处理完成后执行