How can I make sure that I release the cursor if it already exists before I try to open it again?
For a table, I can use something like:
if exists (select top 1 from tempdb.sys.tables where name = '##tmpTable') drop table
But I canβt figure out how to do this for the cursor, for example
-- 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
I do this to clear my script before it starts
The best I can come up with is:
begin try DEALLOCATE someCursorName ; end try begin catch end catch
Is this a good practice?
EDIT: This is a maintennance script. Our highly customizable database clients can have many tables, and the cursor is used to start statistical analysis of the tables - different things happen depending on the types of tables. Basically a lot of dynamic sql. If the script crashes, I would like to repeat the job without worrying about manual intervention. There is only one level of coverage.
Like everyone else, I'm glad to replace the cursors with the given operations. This is what the cursor loops do:
- build sql for reorg / rebuild indexes (initially there was a manual sql for determining DDL to run, and then DDL was released)
- analysis of data distribution and errors in different tables
- find errors in the logs and find the corresponding tables and capture this data (initially there was a manual sql to determine the places where errors were cut out somewhere and templates were inserted to search for errors depending on the types of errors)
source share