Using a cursor with dynamic SQL in a stored procedure

前端 未结 8 2237
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  猫巷女王i
    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.

提交回复
热议问题