Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep getting 'cursor is READ-ONLY'

My code seems pretty forward.

I want to update a specific field with a unique counter, not equal {1,2,3,...}.

I keep getting the error 'The cursor is READ ONLY.'

Also: is there a simpler way?

declare @MaxVal int = NULL
declare @fetchVal int = NULL
select @MaxVal = MAX(tp_Id)+1 from [<tableContainingInitialMaxval>] 
/** some default **/

DECLARE curs01 CURSOR 
for select @maxVal + row_number() OVER (order by [<someUniqueField>]) from [<table2update>];
(used FOR UPDATE OF [<field2update>] but that made no difference)

open curs01
FETCH NEXT FROM curs01 INTO @fetchVal;
WHILE @@FETCH_STATUS = 0
    begin
        update [<table2update>] set [<field2update>] =  @fetchVal 
        WHERE CURRENT OF curs01;
        FETCH NEXT FROM curs01 INTO @fetchVal;
    end;
CLOSE curs01;
DEALLOCATE curs01;
GO 
like image 494
Peter Sinon Avatar asked Dec 27 '22 08:12

Peter Sinon


1 Answers

You don't need a cursor for this.

DECLARE @MaxVal INT = NULL

SELECT @MaxVal = MAX(tp_Id) + 1
FROM   tableContainingInitialMaxval;

WITH CTE
     AS (SELECT *,
                @maxVal + row_number() OVER (ORDER BY someUniqueField) AS rn
         FROM   table2update)
UPDATE CTE
SET    field2update = rn  
like image 64
Martin Smith Avatar answered Jan 13 '23 20:01

Martin Smith