Using Dynamic SQL in a Cursor

  • Hi all,

    I'm trying to generate the SQL in the fetch component of a cusror using variables.

    i.e.

    declare z_cursor for

    select storeid from @table

    when I try to run it I get "must declare @table". It has been declared and populated, there are no "go" statements between to clear the variable.

    Can anyone help with a way to use variables in the cursor declare step?

    Thanks

    Mark

  • Try

    set @sql = 'DECLARE z_cursor CURSOR FOR select storeid from ' + @table

    exec sp_executesql @sql

    OPEN z_cursor

    FETCH ....

    CLOSE curs

    DEALLOCATE curs

    Far away is close at hand in the images of elsewhere.
    Anon.

  • Thanks David, worked a charm!!

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply