在 Memory-Optimized 表中应用 IDENTITY

内存优化表支持 IDENTITY(1, 1)。 但是,内存优化表不支持具有 IDENTITY(x, y) 定义的标识列,其中 x != 1 或 y != 1。 IDENTITY 值的解决方法使用 SEQUENCE 对象(序列号)。

首先从要转换为 In-Memory OLTP 的表中删除 IDENTITY 属性。 然后,为表中的列定义一个新的 SEQUENCE 对象。 作为标识列的 SEQUENCE 对象依赖于为使用 NEXT VALUE FOR 语法获取新标识值的列创建 DEFAULT 值的能力。 由于 OLTP In-Memory 不支持 DEFAULT,因此需要将新生成的 SEQUENCE 值传递给 INSERT 语句或执行插入的本机编译存储过程。 以下示例演示了此模式。

-- Create a new In-Memory OLTP table to simulate IDENTITY insert  
-- Here the column C1 was the identity column in the original table  
--  
create table T1  
(  
  
[c1] integer not null primary key T1_c1 nonclustered,  
[c2] varchar(32) not null,  
[c3] datetime not null  
  
) with (memory_optimized = on)  
go  
  
-- This is a sequence provider that will give us values for column [c1]  
--  
create sequence usq_SequenceForT1 as integer start with 2 increment by 1  
go  
  
--   insert a sample row using the sequence  
--   note that a new value needs to be retrieved form   
--   the sequence object for every insert  
--  
declare @c1 integer = next value for [dbo].[usq_SequenceForT1]  
insert into T1 values (@c1, 'test', getdate())  

多次执行插入操作后,您将在列 [c1] 中看到有效的单调递增值。 此结果集是使用表扫描和哈希索引而未使用ORDER BY生成的,因此行未排序。

另请参阅

迁移到 In-Memory OLTP