简体   繁体   中英

Sequence Numbering in SQL Server

I have an table (always ordered by ID ascending) with 5 records as such:

ID  Sequence
1   1
2   2
3   3
4   4
8   3
9   3

And the desired output is:

ID  Sequence
1   1
2   2
3   3
4   6
8   4
9   5

Looks like 3 direct updates to me, no point over complicating it:

UPDATE table SET sequence = 6 WHERE id = 4 
UPDATE table SET sequence = 4 WHERE id = 8
UPDATE table SET sequence = 5 WHERE id = 9

If you want to do this in one step:

update t
    set sequence = v.sequence
    from t join
         (values (4, 6), (8, 4), (9, 5)
         ) v(id, sequence)
         on t.id = v.id;

If you have to do many of these updates, then separate calls to update incur extra overhead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM