Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an integer variable not accepted as a value for START WITH in sequence

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
like image 410
RAKESH HOLKAR Avatar asked Nov 18 '13 07:11

RAKESH HOLKAR


People also ask

What is the default value of start with clause in sequence?

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.

How do you insert a sequence of numbers in SQL?

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.

How can I change the current value of a sequence in SQL Server?

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.

How get next value from sequence in SQL Server?

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.


1 Answers

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).

like image 191
Szymon Avatar answered Sep 30 '22 13:09

Szymon