共用方式為


移轉計算數據列

記憶體優化資料表不支援計算欄位。 不過,您可以模擬計算欄位。

當您將磁碟資料表移轉至記憶體優化資料表時,您應該考慮需持續保存已計算的欄位。 記憶體優化數據表和原生編譯預存程式的不同效能特性可能會否定持續性的需求。

非持久化計算資料欄位

若要模擬非持久化計算欄位的效果,請在記憶體優化數據表上建立檢視表。 在定義檢視的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  

另請參閱

移轉至 In-Memory OLTP