如何创建带有使用序列的列的表?


10

我有以下

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

我想在MyTable上插入新记录,并将ID设置为序列的下一个值。我该怎么做?触发,或者还有其他方法吗?怎么样?

当我使用SQL Server 2012时,由于gap bug我不想使用身份

Answers:


16

将其分配为列的默认属性

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

将来的读者,如果服务意外停止,则Sequence 可能会有空白,因此CACHE中实体的值可能会丢失。在这里,他们指定no cache通过对序列对象降低性能的权衡来减轻这种情况。

创建序列参考


cache在这种情况下使用安全吗?在连接链接上,Microsoft告诉我们使用no cache
BrunoLM 2013年

@BrunoLM这取决于我们正在谈论的数据库大小,以及我们正在谈论的每秒/分钟有多少事务。
Techie Joe

2

SEQUENCEINSERT语句中使用,您可以尝试以下操作:

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

NEXT VALUE FOR dbo.MyTableID是用于从获取下一个数字的语法SEQUENCE


0

您可以将一个序列用于多个表,如以下示例所示:

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

输出:

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

sqlfiddle

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.