Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create sequence in SQL Server 2008

I am creating sequence in SQL Server with the following code. But it displays error as unknown object type. Please give a solution

Here's my code :

create sequence seqval start with 100 increment by 1 minvalue 0 maxvalue 0 no cycle  
 no cache;

thanks in advance

like image 570
punitha Avatar asked Mar 23 '13 08:03

punitha


1 Answers

You can do this.

--Create a dummy TABLE to generate a SEQUENCE. No actual records will be stored.
CREATE TABLE SequenceTABLE
(
    ID BIGINT IDENTITY  
);
GO

--This procedure is for convenience in retrieving a sequence.
CREATE PROCEDURE dbo.GetSEQUENCE ( @value BIGINT OUTPUT)
AS
    --Act like we are INSERTing a row to increment the IDENTITY
    BEGIN TRANSACTION;
    INSERT SequenceTABLE WITH (TABLOCKX) DEFAULT VALUES;
    ROLLBACK TRANSACTION;
    --Return the latest IDENTITY value.
    SELECT @value = SCOPE_IDENTITY();
GO

--Example execution
DECLARE @value BIGINT;
EXECUTE dbo.GetSEQUENCE @value OUTPUT;
SELECT @value AS [@value];
GO
like image 76
Graeme Avatar answered Oct 11 '22 18:10

Graeme