Sql-Server-2014
了解表分區中索引的重新創建
我需要你的幫助。我有
$$ AdventureWorks2014 $$數據庫,我想對$$ Production $$.$$ TransactionHistoryArchive $$表基於$$ TransactionDate $$柱子。$$ Production $$.$$ TransactionHistoryArchive $$表具有主鍵聚集的 PK_TransactionHistoryArchive_TransactionID。我更喜歡使用嚮導,在嚮導結束時,我使用以下腳本:
USE [AdventureWorks2014] GO BEGIN TRANSACTION CREATE PARTITION FUNCTION [myFUNCTION](datetime) AS RANGE LEFT FOR VALUES (N'2011-12-31T23:59:59.997', N'2012-12-31T23:59:59.997', N'2013-12-31T23:59:59.997') CREATE PARTITION SCHEME [mySCHEMA] AS PARTITION [myFUNCTION] TO ([DRIVE E], [DRIVE F], [DRIVE G], [DRIVE H]) ALTER TABLE [Production].[TransactionHistoryArchive] DROP CONSTRAINT [PK_TransactionHistoryArchive_TransactionID] ALTER TABLE [Production].[TransactionHistoryArchive] ADD CONSTRAINT [PK_TransactionHistoryArchive_TransactionID] PRIMARY KEY NONCLUSTERED ([TransactionID] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) CREATE CLUSTERED INDEX [ClusteredIndex_on_mySCHEMA_636976799895259162] ON [Production].[TransactionHistoryArchive] ([TransactionDate]) WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [mySCHEMA]([TransactionDate]) DROP INDEX [ClusteredIndex_on_mySCHEMA_636976799895259162] ON [Production].[TransactionHistoryArchive] COMMIT TRANSACTION
如果我弄錯了,請幫助我清楚地了解索引創建並糾正我。
我的理論:為了執行表分區,我們需要將聚集索引分配給
$$ TransactionDate $$柱子。為了做到這一點,我們需要改變主鍵約束$$ PK_TransactionHistoryArchive_TransactionID $$從主鍵集群到主鍵非集群。SQL 在以下查詢的幫助下執行此操作:
ALTER TABLE [Production].[TransactionHistoryArchive] DROP CONSTRAINT [PK_TransactionHistoryArchive_TransactionID] ALTER TABLE [Production].[TransactionHistoryArchive] ADD CONSTRAINT [PK_TransactionHistoryArchive_TransactionID] PRIMARY KEY NONCLUSTERED ([TransactionID] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
現在 SQL 可以為
$$ TransactionDate $$柱子:
CREATE CLUSTERED INDEX [ClusteredIndex_on_mySCHEMA_636976799895259162] ON [Production].[TransactionHistoryArchive] ([TransactionDate]) WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [mySCHEMA]([TransactionDate])
在最後一部分中,SQL 刪除了創建的索引(不理解這部分。SQL 怎麼會創建然後立即刪除該聚集索引?):
DROP INDEX [ClusteredIndex_on_mySCHEMA_636976799895259162] ON [Production].[TransactionHistoryArchive]
不需要刪除索引,這可能是嚮導輸出中的編碼疏忽。看來您不只是盲目地執行生成的程式碼;這是一件好事™,這就是為什麼我更喜歡手動編寫自己的 T-SQL 語句。
將聚集主鍵修改為非聚集主鍵,然後將聚集索引添加到單獨列的過程與您描述的完全相同:
- DROP 主鍵約束。
- 使用 NONCLUSTERED 關鍵字添加新的主鍵約束。
- 在所需列上創建聚集索引。
該
DROP INDEX
聲明當然不是必需的。