SQL update records with incrementing value starting from 1 each time

一世执手 提交于 2019-12-06 12:06:57

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!