内存优化表中不支持计算列。 但是,可以模拟一个计算列。
在将基于磁盘的表迁移到内存优化表时,您应该考虑计算列持久化的需要。 内存优化表和本机编译存储过程的不同性能特征可能会否定持久性的需求。
非持久计算列
若要模拟非持久化计算列的效果,请在内存优化表上创建视图。 在定义视图的 SELECT 语句中,将计算列定义添加到视图中。 除了在本地编译的存储过程中,使用计算列值的查询应从视图中读取。 在本机编译的存储过程内,应根据计算列定义更新任何选择、更新或删除语句。
-- Schema for the table dbo.OrderDetails:
-- OrderId int not null primary key,
-- ProductId int not null,
-- SalePrice money not null,
-- Quantity int not null,
-- Total money not null
--
-- Total is computed as SalePrice * Quantity and is not persisted.
CREATE VIEW dbo.v_order_details AS
SELECT
OrderId,
ProductId,
SalePrice,
Quantity,
Quantity * SalePrice AS Total
FROM dbo.order_details
持久化计算列
若要模拟持久化计算列的效果,请创建一个存储过程,用于插入表中,另一个存储过程用于更新表。 插入或更新表时,调用这些存储过程来执行这些任务。 在存储过程内,根据输入计算计算字段的值,类似于在基于磁盘的原始表上定义计算列。 然后,根据需要在存储过程内插入或更新表。
-- Schema for the table dbo.OrderDetails:
-- OrderId int not null primary key,
-- ProductId int not null,
-- SalePrice money not null,
-- Quantity int not null,
-- Total money not null
--
-- Total is computed as SalePrice * Quantity and is persisted.
-- we need to create insert and update procedures to calculate Total.
CREATE PROCEDURE sp_insert_order_details
@OrderId int, @ProductId int, @SalePrice money, @Quantity int
WITH NATIVE_COMPILATION, SCHEMABINDING, EXECUTE AS OWNER
AS BEGIN ATOMIC WITH (LANGUAGE = N'english', TRANSACTION ISOLATION LEVEL = SNAPSHOT)
-- compute the value here.
-- this stored procedure works with single rows only.
-- for bulk inserts, accept a table-valued parameter into the stored procedure
-- and use an INSERT INTO SELECT statement.
DECLARE @total money = @SalePrice * @Quantity
INSERT INTO dbo.OrderDetails (OrderId, ProductId, SalePrice, Quantity, Total)
VALUES (@OrderId, @ProductId, @SalePrice, @Quantity, @total)
END
GO
CREATE PROCEDURE sp_update_order_details_by_id
@OrderId int, @ProductId int, @SalePrice money, @Quantity int
WITH NATIVE_COMPILATION, SCHEMABINDING, EXECUTE AS OWNER
AS BEGIN ATOMIC WITH (LANGUAGE = N'english', TRANSACTION ISOLATION LEVEL = SNAPSHOT)
-- compute the value here.
-- this stored procedure works with single rows only.
DECLARE @total money = @SalePrice * @Quantity
UPDATE dbo.OrderDetails
SET ProductId = @ProductId, SalePrice = @SalePrice, Quantity = @Quantity, Total = @total
WHERE OrderId = @OrderId
END
GO