How to get the next number in a sequence

前端 未结 9 1076
死守一世寂寞
死守一世寂寞 2020-12-04 01:48

I have a table like this:

+----+-----------+------+-------+--+
| id | Part      | Seq  | Model |  |
+----+-----------+------+-------+--+
| 1  | Head      | 0         


        
9条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 02:24

    I would not try to store the Seq value in the table in the first place.

    As you said in the comments, your ID is IDENTITY, which increases automatically in a very efficient and concurrent-safe way by the server. Use it for determining the order in which rows were inserted and the order in which the Seq values should be generated.

    Then use ROW_NUMBER to generate values of Seq partitioned by Model (the sequence restarts from 1 for each value of Model) as needed in the query.

    SELECT
        ID
        ,Part
        ,Model
        ,ROW_NUMBER() OVER(PARTITION BY Model ORDER BY ID) AS Seq
    FROM YourTable
    

提交回复
热议问题