不断出现“光标是只读的”

发布于 2024-12-25 23:16:58 字数 778 浏览 0 评论 0原文

我的代码看起来很先进。

我想使用唯一的计数器(不等于 {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 

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 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

混吃等死 2025-01-01 23:16:58

为此,您不需要光标。

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  

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  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文