11

我正在尝试为序列创建动态起始编号,但它不接受变量即。@START_SEQSTART WITH. 请考虑以下代码:-

CREATE PROCEDURE  [dbo].[SP_RESET_SEQ]
AS
DECLARE @START_SEQ INT =0;

BEGIN
SET @START_SEQ = (SELECT MAX(USER_ID)+1 FROM MASTER_USER);
IF OBJECT_ID('SEQ_USER_ID') IS NOT NULL
DROP SEQUENCE [dbo].[SEQ_USER_ID]

CREATE SEQUENCE [dbo].[SEQ_USER_ID] 
 AS [bigint]
 START WITH @START_SEQ
 INCREMENT BY 1
 MINVALUE 1
 MAXVALUE 99999999
 CACHE 
END
4

2 回答 2

12

您可以对动态 SQL 执行相同操作:

CREATE PROCEDURE  [dbo].[SP_RESET_SEQ]
AS
DECLARE @START_SEQ INT =0;

BEGIN
SET @START_SEQ = (SELECT MAX(USER_ID)+1 FROM MASTER_USER);
IF OBJECT_ID('SEQ_USER_ID') IS NOT NULL
DROP SEQUENCE [dbo].[SEQ_USER_ID]

DECLARE @sql NVARCHAR(MAX)

SET @sql = 'CREATE SEQUENCE [dbo].[SEQ_USER_ID] 
 AS [bigint]
 START WITH ' + @START_SEQ
 + 'INCREMENT BY 1
 MINVALUE 1
 MAXVALUE 99999999
 CACHE'

 EXEC(@sql) 
END

正如下面ta.speot.is所指出的(谢谢!), for 的语法CREATE SEQUENCE采用一个常量(请参阅MSDN)。

于 2013-11-18T07:31:40.577 回答
3

上面的另一个例子不适用于我

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);
于 2019-01-02T10:22:23.540 回答