Start position for a reused t- sql cursor?

2019-07-04 01:50发布

I'm working on a stored procedure that uses a cursor on a temporary table (I have read a bit about why cursors are undesirable, but in this situation I believe I still need to use one).

In my procedure I need to step through the rows of the table twice.

Having declared the cursor, already stepped through the temporary table once and closed the cursor, would the position of the cursor remain at the end of the table when re-opened or does it reposition itself to the initial starting position (ie: before the first row)?

Alternatively, to reposition the cursor must I do a 'FETCH FIRST' before stepping through again?

Am I right to assume the 'cost' of doing this repositioning and reusing the cursor would be less than deallocating and reallocating the cursor?

1条回答
Juvenile、少年°
2楼-- · 2019-07-04 02:18

The allocation and deallocation costs are trivial. The "badness" of a cursor comes from the fact that you're not interacting with the DB in an optimal manner, not from any particular overhead of creating or disposing of a cursor.

I don't think the behavior of the position of a closed and reopened cursor is documented, so you shouldn't depend on it acting in any given way. So, you should reposition it yourself when you start using it again.

And, it's possible that what you're doing might be doable without a cursor. I'd consider asking (a different) question related to that if I were you. :)

查看更多
登录 后发表回答