使用递增整数更新表中所有行的列

时间:2017-03-09 21:24:46

标签: sql tsql

我有一个包含2列的表:

name | order
------------
foo    0
bar    0
john   0
doe    0

我想创建一个SQL更新,它将通过名称列对它们进行排序,例如:

name | order
------------
foo    2
bar    0
john   3
doe    1

这适用于SQL Server。

我已经看到类似这样的东西可用于插入,但显然不能用于更新。

insert into [dbo].[MyTable](Order)
  select row_number() over (order by Name)
  FROM [dbo].[MyTable]

1 个答案:

答案 0 :(得分:5)

使用row_number()

select 
    name
  , row_number() over (order by name)-1 as [order]
from t

有关更新:使用common table expression (cte)

;with cte as (
  select 
      name
    , [order]
    , row_number() over (order by name)-1 as [NewOrder]
  from t
)
update cte
  set [order] = NewOrder;

rextester演示:http://rextester.com/VSF47884

返回:

+------+-------+
| name | order |
+------+-------+
| foo  |     2 |
| bar  |     0 |
| john |     3 |
| doe  |     1 |
+------+-------+

您可以跳过公用表表达式并只使用子查询,但我认为使用cte更容易阅读。

update s
  set [order] = NewOrder
from (
  select 
      name
    , [order]
    , row_number() over (order by name)-1 as [NewOrder]
  from t
  ) as s