I am trying to create dynamic start number for sequence but it is not accepting variable viz. @START_SEQ
for START WITH
. Please consider following code : -
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
Sequence Defaults Start value - the minimum value for the datatype. For a bigint, this is -9223372036854775808. For a tinyint, this is 0. Increment - The default increment is 1.
The syntax to create a sequence in SQL Server (Transact-SQL) is: CREATE SEQUENCE [schema.] sequence_name [ AS datatype ] [ START WITH value ] [ INCREMENT BY value ] [ MINVALUE value | NO MINVALUE ] [ MAXVALUE value | NO MAXVALUE ] [ CYCLE | NO CYCLE ] [ CACHE value | NO CACHE ]; AS datatype.
Sequences are integer values and can be of any data type that returns an integer. The data type cannot be changed by using the ALTER SEQUENCE statement. To change the data type, drop and create the sequence object.
In the case of an INSERT ... SELECT or INSERT ... EXEC statement where the data being inserted comes from a query using an ORDER BY clause, the values being returned by the NEXT VALUE FOR function will be generated in the order specified by the ORDER BY clause.
You can do the same with dynamic 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
As noted by ta.speot.is below (thanks!), the syntax for CREATE SEQUENCE
takes a constant (see MSDN).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With