如何批量更新表

时间:2016-02-15 13:54:58

标签: c# sql sql-server sql-server-2014

假设我有一个看起来像这样的表:

+----+-----------+------+-------+--+
| id | Part      | Seq  | Model |  |
+----+-----------+------+-------+--+
| 1  | Head      | 0    | 3     |  |
| 2  | Neck      | 1    | 3     |  |
| 3  | Shoulders | 11   | 3     |  |
| 4  | Groin     | 2    | 3     |  |
| 5  | Stomach   | 5    | 3     |  |
+----+-----------+------+-------+--+

如您所见,Seq字段是这些项目将在前端显示的顺序。这是Seq 0,1,2,5,11。现在用户想要重新排序列表。如果他们希望Stomach(id:5)拥有seq: 0,我将如何编写查询来更新仅模型3的所有Seq值?

1 个答案:

答案 0 :(得分:0)

这是一种将序列号重新指定为有序整数的方法,首先是“胃”:

with toupdate as (
      select t.*,
             row_number() over (partition by model -- not really necessary
                                order by (case when Part = 'Stomach' then -1
                                               else seq
                                          end)
                               ) as newseq
      from t
      where model = 3
     )
update toupdate
    set seq = newseq;