开发者

TSQL - Auto Increment in an UPDATE statement

开发者 https://www.devze.com 2023-03-26 08:13 出处:网络
SQL Server 2005 I have a table containing the following: - [order_id][index_1] 6000200010 6000200020 6000200020

SQL Server 2005

I have a table containing the following: -

[order_id]     [index_1]
600020001      0
600020002      0
600020002      0
600020002      0
600020003      0
...

which needs to be updated to: -

[order_id]     [index_1]
600020001      1
600020002      1
600020002      2
600020002      3
600020003      1  

I am trying to write an UPDATE statement that will populate the index_1 field, as per the example above. I can acheive this using a CURSOR, but ideally would like to do it without if possible.

For each new order_id the numbering restarts. For each order_id row the index_1 field 开发者_JAVA技巧is incremented by 1.

Is it possible to do this without a cursor?


You can use a CTE and row_number() to do what you want. The table @T in the code below is only for demonstration. Replace @T with whatever your table is called.

declare @T table ([order_id] int, [index_1] int)

insert into @T values
(600020001,      0),
(600020002,      0),
(600020002,      0),
(600020002,      0),
(600020003,      0)

;with cte as
(
  select index_1,
         row_number() over(partition by order_id order by (select 1)) as rn
  from @T       
)
update cte 
  set index_1 = rn

select *
from @T

Result:

order_id    index_1
----------- -----------
600020001   1
600020002   1
600020002   2
600020002   3
600020003   1
0

精彩评论

暂无评论...
验证码 换一张
取 消