我如何插入-select 一个从变量开始的序列?

How can I insert-select a sequence starting from a variable?

这里有一个关于 SO 的问题,此后已被删除。但是当我在研究解决它的方法时,我正在编写一个避免使用标识列并使用序列本身的脚本:

create table table1(Id int primary key, group_id int, Name varchar(64))
insert into table1(Id, group_id, Name) values (1, 1, 'a'), (2, 1, 'b'), (4, 1, 'c'), (8, 1, 'd')
declare @MaxId as int
select @MaxId = max(Id) + 1 from table1
declare @sql varchar(max)
set @sql = N'CREATE SEQUENCE MySequence  AS INTEGER START WITH ' + cast(@maxId as varchar(10))
exec(@sql)
insert into table1(id, group_id, Name)
select next value for MySequence, 2, Name
from table1
where group_id = 1;

这确实有效,也就是说,它成功地插入了四个具有动态生成的 ID 的记录。

但是

的部分
declare @sql varchar(max)
set @sql = N'CREATE SEQUENCE MySequence  AS INTEGER START WITH ' + cast(@maxId as varchar(10))
exec(@sql)

在我看来非常违反直觉和骇人听闻。

问题:有没有办法定义一个从变量值开始的序列,而不生成文本并执行它?

CREATE SEQUENCE syntax documentation 表明需要常量,因此您不能在 DDL 语句中指定变量。

是的,创建一次性动态序列是一种技巧。

而是使用 ROW_NUMBER(),类似

use tempdb
drop table if exists table1
go
create table table1(id int, group_id int, name varchar(200))

insert into table1(id,group_id,name) values (1,1,'a')
insert into table1(id,group_id,name) values (2,1,'a')

declare @maxValue int = (select max(id) from table1)

insert into table1(id, group_id, Name)
select @maxValue + row_number() over (order by Id), 2, Name
from table1
where group_id = 1;


select * from table1