7

我有一个使用嵌套游标的代码。当我解析它时,SQL Studio 告诉我“命令已成功完成”,但每当我执行时,我都会收到一堆重复的“名称为 '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
4

1 回答 1

11

你不应该DEALLOCATE cursor_stats在循环内。

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

只有在所有处理完成后才这样做

于 2013-07-31T13:46:43.453 回答