在尝试再次打开游标之前,如何确保我已经存在游标?
对于一张桌子,我可以使用类似的东西:
if exists (select top 1 from tempdb.sys.tables where name = '##tmpTable')
drop table ##tmpTable;
... then I can recreate my ##tmpTable
Run Code Online (Sandbox Code Playgroud)
但我无法弄清楚如何为光标做这样的事情
-- First clean up if already exists..
..... <----- what goes here???
-- Declare and use a cursor
DECLARE someCursorName CURSOR
FOR
select something from somewhere
FOR READ ONLY
Run Code Online (Sandbox Code Playgroud)
我这样做是为了确保我的脚本在开始工作之前清理干净
我能想出的最好的是:
begin try DEALLOCATE someCursorName ; end try begin catch end catch
Run Code Online (Sandbox Code Playgroud)
这是一个好习惯吗?
编辑:这是maintennance脚本.在我们大量客户定制的数据库中,可以有许多表,光标用于在表中运行统计分析 - 根据表的类型,会发生不同的事情.基本上很多动态的sql.如果脚本失败,我希望能够重复这项工作而不必担心人工干预.这里只有一个范围.
像所有事情一样,我很乐意用set操作替换游标.这些是游标循环所做的事情: