有人可以向我解释为什么我执行存储过程时出现错误消息。 "A cursor with the name 'tName_cursor' already exists"
DECLARE @tName VARCHAR(100)
DECLARE @lsql VARCHAR(8000)
DECLARE tName_cursor CURSOR FOR
SELECT NAME FROM SYS.tables WHERE TYPE = 'U' AND NAME LIKE 'PPM_METRIC%'
OPEN tName_cursor;
FETCH NEXT FROM tName_cursor INTO @tName;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @lsql = N'
UPDATE [' +@tName+ ']
SET LATESTOFALL_FLG = ''N''
FROM [' +@tName+ '] T
JOIN D_CUSTOM_METRICS_RULE S
ON T.METRIC_ID = S.CUSTOM_METRIC_RULE_ID
AND T.LATESTOFALL_FLG = ''Y'''
EXECUTE sp_executesql @lsql
FETCH NEXT FROM tName_cursor INTO @tName;
END
CLOSE tName_cursor;
DEALLOCATE tName_cursor;
DECLARE tName_cursor_REDO CURSOR FOR
SELECT NAME FROM SYS.tables WHERE TYPE = 'U' AND NAME LIKE 'PPM_METRIC%'
OPEN tName_cursor_REDO;
FETCH NEXT FROM tName_cursor_REDO INTO @tName;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @lsql = N'
UPDATE [' +@tName+ ']
SET LATESTOFDAY_FLG = ''N''
FROM [' +@tName+ '] T
JOIN D_CUSTOM_METRICS_RULE S
ON T.METRIC_ID = S.CUSTOM_METRIC_RULE_ID
AND T.CALC_METRIC_DATE_ID = CONVERT(INT,convert(VARCHAR, getdate(), 112))
AND T.LATESTOFDAY_FLG = ''Y'''
EXECUTE sp_executesql @lsql
FETCH NEXT FROM tName_cursor_REDO INTO @tName;
END
CLOSE tName_cursor_REDO;
DEALLOCATE tName_cursor_REDO;
答案 0 :(得分:2)
看起来像是一些例外或“返回”#39;在DEALLOCATE命令
之前中断执行当您声明&#39>时,可能会发生"一个名为' tName_cursor'的光标已经存在"
消息。块被成功执行,但是在一些代码失败之前' DEALLOCATE tName_cursor'声明。然后,第二次执行存储过程时,它会再次尝试声明游标并弹出错误消息。我建议你添加'开始尝试..结束尝试'阻止你的代码和'打印ERROR_MESSAGE()'在异常块中看看会发生什么。
答案 1 :(得分:0)
听起来你可能正在使用GLOBAL游标(?)。 如果你不需要它们,我建议使用LOCAL游标。 例如
DECLARE tName_cursor_REDO CURSOR LOCAL FOR
SELECT NAME FROM SYS.tables WHERE TYPE = 'U' AND NAME LIKE 'PPM_METRIC%'
这可能有助于使事情更加健全。