A cursor inside another sqlserver cursor

Asked

Viewed 3,605 times

2

I know I could do a tab1 Join with tab2, but that wouldn’t be the case, I need both cursors.

When I run I get error from:

A cursor with the name 'cursor_tab2 ' already exists.

The cursor is already open.

I understand the mistake, but I can’t fix it.

What’s the right way to do it?

I’ve been using.

DECLARE cursor_tab1 CURSOR
    FOR SELECT id FROM tab1
    OPEN cursor_tab1
    FETCH NEXT FROM cursor_tab1
    INTO @idTab1

    WHILE @@FETCH_STATUS = 0
    BEGIN


        DECLARE cursor_tab2 CURSOR
        FOR SELECT id FROM tab2 where id_tab1 = @idTab1
        OPEN cursor_tab2
        FETCH NEXT FROM cursor_tab2
        INTO @idTab2

        WHILE @@FETCH_STATUS = 0
        BEGIN

            ...


        FETCH NEXT FROM cursor_tab2 INTO @idTab2;
        END



    FETCH NEXT FROM cursor_tab1 INTO @idTab1;
    END
  • 1

    Why you need two cursors?

  • There is a whole logic there in the middle, it defined whether or not I will use the second, but it depends on other factors, it is not a simple process... I put the basic code to make it easier to ask and read the answer, I think this makes it easier for the next users to consult.

1 answer

3


First of all it should be said that there are few problems that need cursors to be solved in SQL.

That said, apparently you are not closing and releasing (dealocate) the cursors.

CLOSE cursor_tab2
DEALLOCATE cursor_tab2

If you are and that’s not the problem then declare the cursor as LOCAL.

DECLARE teuCursor CURSOR LOCAL ...
  • perfect. I put the CLOSE and the DEALLOCATE and it worked perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.