Continuing my series on SQL Server 2012, today we will explore Sequence. Sequence is an object in SQL Server 2012 which can be used to generate customized sequence numbers. Sequence is an independent object and is not associated with any table by default. When you are inserting data into the table, we can make use of sequence values from the sequence object.
Consider the following Sequence and data
create sequence my_seq
as int
start with 1
increment by 1
GO
The above creates the sequence named my_seq which has initial value of 1 and will increment by 1
create table sales(sales_id int, product_id int,qty int,sales_amount decimal(12,2))
GO
Let us add some data to this table generating sales_id value using sequence
insert into sales(sales_id,product_id,qty,sales_amount)
select next value for my_seq,10001,3,1200 union all
select next value for my_seq,10002,2,600 union all
select next value for my_seq,10003,10,200 union all
select next value for my_seq,10001,200,1200 union all
select next value for my_seq,10001,10,1200
In the above insert statement, values are taken from sequence for sales_id column and every time a value is selected from the sequence, its value gets incremented by 1
Now run this select statement and see the result
select * from sales
OUTPUT
If you want to restart the sequence values, you can use ALTER sequence statement
alter sequence my_seq restart with 1
No comments:
Post a Comment