13

I have the following

CREATE TABLE [MyTable]
(
    [ID] [bigint] PRIMARY KEY NOT NULL,
    [Title] [nvarchar](64) NOT NULL
)

CREATE SEQUENCE MyTableID
    START WITH 1
    INCREMENT BY 1
    NO CACHE
    ;
GO

I want to insert new records on MyTable and set the ID to the next value of the sequence. How can I do it? A trigger perhaps, or is there some other way? How?

As I am using SQL Server 2012, I don't want to use Identity because of the gap bug.

BrunoLM
  • 3,533
  • 7
  • 28
  • 22

3 Answers3

17

Assign it as the default property for the column

CREATE TABLE [MyTable]
(
    [ID] [bigint] PRIMARY KEY NOT NULL DEFAULT (NEXT VALUE FOR dbo.MyTableID),
    [Title] [nvarchar](64) NOT NULL
);

Future readers, a Sequence can have a gap if the service stops unexpectedly, the value of the entities in CACHE can be lost. Here, they are specifying no cache to mitigate that with the tradeoff of slower performance for the sequence object.

CREATE SEQUENCE reference

Aaron Bertrand
  • 181,950
  • 28
  • 405
  • 624
billinkc
  • 16,143
  • 4
  • 54
  • 89
2

To use a SEQUENCE in an INSERT statement, you could try this:

INSERT INTO [MyTable] ([ID],[TITLE]) VALUES (NEXT VALUE FOR dbo.MyTableID, @TITLE) 

NEXT VALUE FOR dbo.MyTableID is the syntax for obtaining the next number from a SEQUENCE.

Hannah Vernon
  • 70,928
  • 22
  • 177
  • 323
Techie Joe
  • 373
  • 1
  • 3
  • 12
0

You can use one sequence for multiple tables, as demonstrated by the following example:

CREATE SEQUENCE dbo.MyTableID
    START WITH 1
    INCREMENT BY 1
    NO CACHE
    ;
GO

CREATE TABLE dbo.[MyTable1]
(
    [ID] [bigint] PRIMARY KEY NOT NULL DEFAULT (NEXT VALUE FOR dbo.MyTableID),
    [Title1] [nvarchar](64) NOT NULL
);

CREATE TABLE dbo.[MyTable2]
(
    [ID] [bigint] PRIMARY KEY NOT NULL DEFAULT (NEXT VALUE FOR dbo.MyTableID),
    [Title2] [nvarchar](64) NOT NULL
);

--Insert 2 rows
insert into  [MyTable1] (title1)
select 'title11'

insert into  [MyTable1] (title1)
select 'title12';

insert into  [MyTable2] (title2)
select 'title21'

insert into  [MyTable2] (title2)
select 'title22';

select f1.*, 'Into MyTable1' Tb from  [MyTable1] f1
union all
select f1.*, 'Into MyTable2' Tb from  [MyTable2] f1

Output:

+----+---------+---------------+
| ID | Title1  |      Tb       |
+----+---------+---------------+
|  1 | title11 | Into MyTable1 |
|  2 | title12 | Into MyTable1 |
|  3 | title21 | Into MyTable2 |
|  4 | title22 | Into MyTable2 |
+----+---------+---------------+

sqlfiddle

Andriy M
  • 23,261
  • 6
  • 60
  • 103
Esperento57
  • 107
  • 3