Sql-Server

更新索引視圖“線上”

  • May 6, 2019

假設我有一個如下所示的索引視圖:

ALTER VIEW dbo.MyIndexedView WITH SCHEMABINDING
AS 
   SELECT ord.SomeColumn, COUNT_BIG(*) AS Count
   FROM dbo.Ordered ord
   WHERE ord.CreatedWhen >  CONVERT(DATETIME, '2014-11-01', 121)
   GROUP BY ord.SomeColumn
GO

CREATE UNIQUE CLUSTERED INDEX [CIX_MyIndexedView] ON dbo.MyIndexedView (SomeColumn)
GO

如果我更改此視圖中的日期時間值(例如“2014-11-01”),則需要重新生成聚集索引。

有沒有辦法讓現有的視圖和索引保持有效,直到新的視圖和索引完全建構然後讓它們交換? 相似Online=On

這是我將如何做到的。首先,創建幾個備用模式:

CREATE SCHEMA HoldingTank AUTHORIZATION dbo;
CREATE SCHEMA Swapper AUTHORIZATION dbo;

現在,當需要刷新視圖並更改過濾謂詞時,請在HoldingTank架構中創建它:

CREATE VIEW HoldingTank.MyIndexedView
WITH SCHEMABINDING
AS
 SELECT ...
GO

CREATE UNIQUE CLUSTERED INDEX [CIX_MyIndexedView]
ON HoldingTank.MyIndexedView(SomeColumn);

現在,開始一個事務,並交換對象。

BEGIN TRANSACTION;
 ALTER SCHEMA Swapper TRANSFER dbo.MyIndexedView;
 ALTER SCHEMA dbo TRANSFER HoldingTank.MyIndexedView;
COMMIT TRANSACTION;

然後稍後您可以簡單地從以下位置刪除視圖的舊副本Swapper

DROP VIEW Swapper.MyIndexedView;

我在這些部落格文章中詳細介紹了此解決方案:

引用自:https://dba.stackexchange.com/questions/123890