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
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?
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.
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.
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.
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.
You can select the current_value
from sys.sequences
:
SELECT current_value FROM sys.sequences WHERE name = 'OrderNumberSequence' ;
DEMO
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