Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set 'start with' of sequence to select query result in SQL server?

Tags:

sql-server

I am trying to do something like in SQL server 2012

CREATE SEQUENCE item_seq
  START WITH (SELECT MAX(i_item_sk)
     FROM item) 
  INCREMENT BY 1;

Is it possible? What are the other ways if this is not possible? Can we do it like how we do it in PostgreSQL(given below)?

create sequence item_seq 
select setval('item_seq', (select max(i_item_sk)+1 from item), false);

I would be further using this sequence variable in Kettle 'Add sequence' step.

like image 601
VKB Avatar asked Nov 13 '14 16:11

VKB


People also ask

How can we use sequence in select statement in SQL Server?

If you want to select the next value from sequence object, you can use this SQL statement. If you want to select multiple next values from SQL Sequence, you have to loop calling the above SQL statement and save the "next value" got in a storage. You can loop using (while loop) or by (cursor).

How do I select a sequence number in SQL Server?

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

It does not look like you can declare a variable amount in the syntax. However, you can wrap it in an EXEC statement, like so:

DECLARE @max int;
SELECT @max = MAX(i_item_sk)
     FROM item

exec('CREATE SEQUENCE item_seq 
    START WITH ' + @max +
'   INCREMENT BY 1;')

select * from sys.sequences
like image 51
Jason Whitish Avatar answered Oct 14 '22 14:10

Jason Whitish