Pet*_*non 4 sql-server cursor sql-server-2008-r2 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
Run Code Online (Sandbox Code Playgroud)
Mar*_*ith 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1189 次 |
| 最近记录: |