Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current value from a SQL Server SEQUENCE

I want to get the current value from my sequence - the same value that is shown in the sequence properties window SQL Server Management Studio

enter image description here

My sequence is created with this statement:

CREATE SEQUENCE [OrderNumberSequence]     as int     START WITH 4000     INCREMENT BY 1     MINVALUE 0     NO MAXVALUE     NO CACHE; GO 

I have tried this SQL from MSDN – but the result is that my number is increasing with 5 for every time I run the query

DECLARE     @FirstSeqNum sql_variant , @LastSeqNum sql_variant , @CycleCount int , @SeqIncr sql_variant , @SeqMinVal sql_variant , @SeqMaxVal sql_variant ;  EXEC sys.sp_sequence_get_range @sequence_name = N'[OrderNumberSequence]' , @range_size = 5 , @range_first_value = @FirstSeqNum OUTPUT  , @range_last_value = @LastSeqNum OUTPUT  , @range_cycle_count = @CycleCount OUTPUT , @sequence_increment = @SeqIncr OUTPUT , @sequence_min_value = @SeqMinVal OUTPUT , @sequence_max_value = @SeqMaxVal OUTPUT ;  -- The following statement returns the output values SELECT   @FirstSeqNum AS FirstVal , @LastSeqNum AS LastVal , @CycleCount AS CycleCount , @SeqIncr AS SeqIncrement , @SeqMinVal AS MinSeq , @SeqMaxVal AS MaxSeq ; 

Is there a way that I can get the value without changing the number?

like image 985
Henrik Stenbæk Avatar asked Dec 04 '12 12:12

Henrik Stenbæk


People also ask

How do I get the current value of a sequence in SQL?

You can access the value of a sequence using the NEXTVAL or CURRVAL operators in SQL statements. You must qualify NEXTVAL or CURRVAL with the name (or synonym) of a sequence object that exists in the same database, using the format sequence. NEXTVAL or sequence. CURRVAL.

How get next value from sequence in SQL Server?

SELECT - For each referenced sequence object, a new value is generated once per row in the result of the statement. INSERT ... VALUES - For each referenced sequence object, a new value is generated once for each inserted row in the statement.

How do you query a sequence in SQL?

The syntax to a view the properties of a sequence in SQL Server (Transact-SQL) is: SELECT * FROM sys. sequences WHERE name = 'sequence_name'; sequence_name.

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.


1 Answers

You can select the current_value from sys.sequences:

SELECT current_value FROM sys.sequences WHERE name = 'OrderNumberSequence' ; 

DEMO

like image 182
Tim Schmelter Avatar answered Sep 23 '22 09:09

Tim Schmelter