生成行计数,每行增加 10,000 行

  • 本文关键字:增加 sql sql-server tsql
  • 更新时间 :
  • 英文 :


我需要返回一个生成的 ID,其中每行增加 10,000。

例如,下面的"预期结果"列,如果有更多的行,则每次将增加 10,000。

Create Table #temp
(
ID uniqueidentifier,
ExpectedResult int
)
insert into #temp
(
ID,
ExpectedResult
)
select
NEWID(),
10000
union
select
NEWID(),
20000
union
select
NEWID(),
30000
union
select
NEWID(),
40000
union
select
NEWID(),
50000
select * from #temp
order by ExpectedResult
drop table #temp

我找到了下面的示例,但我不确定每次如何将计数增加 10,000

ROW_NUMBER() OVER (ORDER BY (SELECT 100))

如果您使用的是 SQL Server 2012 或更高版本(包括 SQL Server 2017(,则可以使用CREATE SEQUENCE创建编号序列。 要创建增量为 10000 的 SEQUENCE,请将子句添加INCREMENT BY

例如:

CREATE SEQUENCE Test.CountBy1  
START WITH 10000  
INCREMENT BY 10000  

有关详细信息,请参阅有关CREATE SEQUENCE的 SQL Server 文档: https://learn.microsoft.com/sql/t-sql/statements/create-sequence-transact-sql?view=sql-server-2017

您可以使用cteguids生成N number。下面是一个示例 cte,用于为您的guid生成 100 行。

Drop table #temp
Create Table #temp
(
ID uniqueidentifier,
ExpectedResult int
);
with cte as(
select  newid() as new_id, 10000 as ctr
union all 
select new_id, ctr + 10000 from cte where ctr/10000 < 100
)
insert into #temp
select * from cte  option (MaxRecursion 0 );

select * from #temp;

您需要将 ROW_NUMBER(( 除以 10000,然后乘以 10000 你可以写这样的东西

select *, rowNum10K = 10000 * (1 + (row_number() over (order by object_id)) / 10000)
from #temp

正如 Nick 在原始问题评论中所建议的那样,这样做了:

ROW_NUMBER() OVER (ORDER BY (SELECT 100))*10000

您可以将列定义为identity来为您执行此操作:

Create Table temp (
ID uniqueidentifier,
ExpectedResult int identity (10000, 10000)
);
insert into temp (ID)
select v.id
from (values (NEWID()), (NEWID()), (NEWID()), (NEWID()), (NEWID())) v(id);

这是一个数据库<>小提琴。

最新更新