继续'光标是只读'

时间:2012-01-11 15:43:21

标签: sql-server sql-server-2008-r2 cursor sql-update

我的代码看起来非常好。

我想使用唯一的计数器更新特定字段,不等于{1,2,3,...}。

我一直收到错误'光标只读。'

另外:有更简单的方法吗?

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 

1 个答案:

答案 0 :(得分:10)

您不需要光标。

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