为什么不接受整数变量作为按顺序开始的值

cwxwcias  于 2022-09-18  发布在  Java
关注(0)|答案(3)|浏览(112)

我正在尝试为序列创建动态开始编号,但它不接受变量VIZ。@START_SEQ表示START 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
cunj1qz1

cunj1qz11#

您可以对动态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所指出的(谢谢!),CREATE SEQUENCE的语法接受一个常量(参见MSDN)。

hvvq6cgz

hvvq6cgz2#

上例中的另一个不适用于我

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);
ruarlubt

ruarlubt3#

在CREATE SEQUENCE中不需要作为整数

将@MaxBookingId声明为int;
SELECT@MaxBookingID=max(Bookingid)from Booking;
声明@s nvarchar(4000);
设置@s=N‘
创建序号发票_序号
以‘+cast(@MaxBookingID as nvarchar)+’开头
递增1
没有循环;‘
Exec(@s);

此脚本非常适合集成到增量分发中

相关问题