Using a cursor with dynamic SQL in a stored procedure

前端 未结 8 2200
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 21:37

I have a dynamic SQL statement I\'ve created in a stored procedure. I need to iterate over the results using a cursor. I\'m having a hard time figuring out the right syntax.

相关标签:
8条回答
  • 2020-11-29 22:14

    First off, avoid using a cursor if at all possible. Here are some resources for rooting it out when it seems you can't do without:

    There Must Be 15 Ways To Lose Your Cursors... part 1, Introduction

    Row-By-Row Processing Without Cursor

    That said, though, you may be stuck with one after all--I don't know enough from your question to be sure that either of those apply. If that's the case, you've got a different problem--the select statement for your cursor must be an actual SELECT statement, not an EXECUTE statement. You're stuck.

    But see the answer from cmsjr (which came in while I was writing) about using a temp table. I'd avoid global cursors even more than "plain" ones....

    0 讨论(0)
  • 2020-11-29 22:18

    Working with a non-relational database (IDMS anyone?) over an ODBC connection qualifies as one of those times where cursors and dynamic SQL seems the only route.

    select * from a where a=1 and b in (1,2)
    

    takes 45 minutes to respond while re-written to use keysets without the in clause will run in under 1 second:

    select * from a where (a=1 and b=1)
    union all
    select * from a where (a=1 and b=2)
    

    If the in statement for column B contains 1145 rows, using a cursor to create indidivudal statements and execute them as dynamic SQL is far faster than using the in clause. Silly hey?

    And yes, there's no time in a relational database that cursor's should be used. I just can't believe I've come across an instance where a cursor loop is several magnitudes quicker.

    0 讨论(0)
提交回复
热议问题