如何从表的Max Id开始生成Sequence

时间:2017-02-16 13:46:38

标签: sql-server sequence

我正在尝试使用此DML创建序列,我收到此错误:

  

@ maxBookingId'附近的语法不正确。

代码:

 DECLARE @maxBookingId AS INT 

 SELECT @maxBookingId = MAX(bookingid) 
 FROM booking

 CREATE SEQUENCE Invoice_Seq  AS INTEGER  
 START WITH @maxBookingId
 INCREMENT BY 1  
 NO CYCLE;

如何解决此问题?

2 个答案:

答案 0 :(得分:5)

不幸的是,这里没有变数。请改用动态SQL:

declare @maxBookingId as int 
select @maxBookingId = max(bookingid) from booking
declare @s nvarchar(4000);
set @s = N'
CREATE SEQUENCE Invoice_Seq  AS INTEGER  
START WITH ' + cast(@maxBookingId as nvarchar) + '
INCREMENT BY 1  
NO CYCLE;'

EXEC (@s);

答案 1 :(得分:2)

documentation表明它必须是常量。要解决它,您应该能够使用动态SQL。