0

I'm trying to insert invoice items to existing invoice with negative value for quantity. I decided to use cursor for this but when I run the query it results in infinite loop.

Here is my code:

declare @cKey char(13);
set @cKey = '1512000000043';

-- declare cursor to get
-- all items for specific invoice
declare c cursor
for
    select
        acIdent, anQty
    from
        tHE_MoveItem where acKey = @cKey;

declare @cIdent  char (16),
        @nQty decimal(19,6),
        @nNo int,
        @cStatus varchar(2),   
        @cErrorOut varchar(1024);
open c
fetch c into @cIdent, @nQty
while (@@fetch_status=0)
begin

    -- add all items with negative qty
    -- to same invoice
    select @cIdent;
    -- invert value
    set @nQty = @nQty *-1;
    select @nQty;

    -- insert ident with negative value to invoice
    EXEC dbo.pHE_MoveItemsCreAll @cKey, @cIdent,@nQty, '', 1, @nNo OUTPUT,@cErrorOut OUTPUT,@cStatus OUTPUT;

    fetch c into @cIdent, @nQty
end

close c
deallocate c

I'm using SQL Server 2008 R2.

The procedure pHE_MoveItemsCreAll is inserting values in same table as the cursor reads from.

5
  • It is not quite clear from your code - are you inserting records into the same table you're reading from? Commented Apr 28, 2015 at 6:58
  • Yes the procedure is inserting in same table. Commented Apr 28, 2015 at 6:59
  • How do you conclude that your code block went to infinite loop.? May be Procedure execution take more time also. Comment that proc execution and try Commented Apr 28, 2015 at 7:06
  • @knkarthick24 becouse invoice only had one item on it and after i force closed the execution it had 500+ rows :) Commented Apr 28, 2015 at 7:07
  • Answer is already added by @AndyKorneyev. modify your code accordingly. Commented Apr 28, 2015 at 7:10

1 Answer 1

4

You have to declare your cursor using static keyword (declare c cursor static) to prevent fetching newly inserted records back to cursor.

A static cursor always displays the result set as it was when the cursor was opened. In other case when you're inserting your records into the same table and they met conditions of data selected into cursor - these new records will be retrieved and cursor iterates again.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I totaly forgot about static. Now it works like a charm :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.