开发者

SQL update records with incrementing value starting from 1 each time

开发者 https://www.devze.com 2023-01-15 16:40 出处:网络
I am adding batches of records to a table using a single insert statement.I want each new batch to be allocated incrementing numbers, but starting from 1 each time.

I am adding batches of records to a table using a single insert statement. I want each new batch to be allocated incrementing numbers, but starting from 1 each time.

So, if I have

Batch    Name    IncementingValue
1        Joe     1
1        Pete    2
1        Andy    3
2        Sue     1
2        Mike    2
2        Steve   3

and I then add two records (using a single insert statement) :

3        Dave
3        Paul

How can I run an update statement against this table so that Dave will be set to 1 a开发者_如何学Cnd Paul to 2. I don't want to use a cursor.


The ranking function ROW_NUMBER should do what you need. You didn't mention any specific rules about how the sequence number should be allocated, so I've done it here using the name:

INSERT targetTable(Batch,Name,IncementingValue)
SELECT BatchId,
       Name,
       ROW_NUMBER() OVER (ORDER BY Name)
FROM sourceTable


I needed to accomplish something similar with dates and formatted numbers.

Hopefully, someone will find this example useful.

    update TEST_TABLE 
    set ref = reference
          from (
                      select 
                          *, 
                          (CONVERT(VARCHAR(10),GETDATE(),12) + RIGHT('0000' + CAST(ROW_NUMBER() OVER (ORDER BY id) AS VARCHAR(4)), 4)) as reference 
                      from TEST_TABLE
                      WHERE 
                    test_table.id > 4
                        and
                    test_table.id < 8 
                ) TEST_TABLE
0

精彩评论

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