在sql select中生成序列

时间:2009-07-22 15:53:00

标签: sql-server

我需要编写一个查询,为每条记录生成一种有序的ID ...例如:

ID      Customer Name
-------------------------
C1000   customer #1
C1010   customer #2
C1020   customer #3
C1030   customer #4

现在,这些“C1000”ID不存在......只有客户名称。我需要在选择时生成它们...所以我可以保存输出,然后导入到新系统中。

我该怎么做:


select 
   'C' + (some kinda code/math that generates the count based on a sequence?  or row number?),
   name
from Customers

=============================================== =

我最终执行了以下操作(因此我可以配置start#和增量大小):


DECLARE @start int; 
DECLARE @inc int; 
set @start = 1000; 
set @inc = 10; 

Select 'C' + CAST(@start + (@inc * (ROW_NUMBER() OVER (ORDER BY name))) as varchar) as NewID, Name
from customer

1 个答案:

答案 0 :(得分:2)

使用ROW_NUMBER()中的this example