我目前有一个相当大的表(500万到700万行)。此表定期通过在暂存表中构建数据的过程重新生成,然后使用ALTER TABLE .. SWITCH TO ..语句将数据切换到生产表中。
示例:
BEGIN TRAN;
-- Rebuild indexes
ALTER INDEX IX_NC_GroupEvent_staging_GroupName on [dbo].[GroupEvent_staging]
REBUILD;
ALTER INDEX IX_NC_GroupEvent_staging_Created ON [dbo].[GroupEvent_staging]
REBUILD;
-- Empty production table
TRUNCATE TABLE [dbo].[GroupEvent];
-- Switch data from staging-table into production table
ALTER TABLE [dbo].[GroupEvent_staging] SWITCH TO [dbo].[GroupEvent]
COMMIT;执行此操作时,是否也会切换索引的当前状态(如果愿意,则切换索引数据)?我提出这个问题,有两个原因:
1)为了执行SWITCH TO语句,一个要求是源表和目标表都必须包含相同的索引。这让我相信索引数据可能也会被转换,但我不知道如何验证这一点。
( 2)以这种方式构建表格的主要好处是避免在使用时对生产表进行过多的工作。当然,如果我能够在分阶段表上重建索引,并将重建的索引与表一起切换到生产索引,我将感到非常高兴。
发布于 2016-06-17 14:14:06
索引数据也会被切换吗?
是。如果不这样做,那将是很奇怪的,因为查询会返回错误的结果,或者我们必须在切换后手动重建索引。
我不知道怎么证明
一种方法就是尝试一下
CREATE TABLE [dbo].[GroupEvent]
(
GroupName VARCHAR(100) INDEX IX_NC_GroupEvent_staging_GroupName,
Created DATETIME INDEX IX_NC_GroupEvent_staging_Created
);
CREATE TABLE [dbo].[GroupEvent_staging]
(
GroupName VARCHAR(100) INDEX IX_NC_GroupEvent_staging_GroupName,
Created DATETIME INDEX IX_NC_GroupEvent_staging_Created
);
INSERT INTO [dbo].[GroupEvent_staging]
VALUES ('Group1',GETDATE()),
('Group2',GETDATE());
ALTER INDEX IX_NC_GroupEvent_staging_GroupName ON [dbo].[GroupEvent_staging] REBUILD;
ALTER INDEX IX_NC_GroupEvent_staging_Created ON [dbo].[GroupEvent_staging] REBUILD;
SELECT index_id,
allocated_page_file_id,
allocated_page_page_id
FROM sys.dm_db_database_page_allocations(DB_ID(), OBJECT_ID('[dbo].[GroupEvent_staging]'), NULL, NULL, 'DETAILED')
WHERE is_allocated = 1;
-- Empty production table
TRUNCATE TABLE [dbo].[GroupEvent];
-- Switch data from staging-table into production table
ALTER TABLE [dbo].[GroupEvent_staging] SWITCH TO [dbo].[GroupEvent];
SELECT index_id,
allocated_page_file_id,
allocated_page_page_id
FROM sys.dm_db_database_page_allocations(DB_ID(), OBJECT_ID('[dbo].[GroupEvent]'), NULL, NULL, 'DETAILED')
WHERE is_allocated = 1;
SELECT GroupName
FROM [dbo].[GroupEvent];
DROP TABLE [dbo].[GroupEvent], [dbo].[GroupEvent_staging]; 在返回这两行的过程中访问的唯一对象是显示数据必须已切换的索引。

上面还比较了开关之前来自sys.dm_db_database_page_allocations for GroupEvent_Staging的结果和切换后对GroupEvent的类似查询,以发现对于堆本身(index_id=0)和两个非聚集索引(ID2-3),页面保持不变。这显示开关是元数据,只有已分配的页面的所有权才被转移。

https://dba.stackexchange.com/questions/141530
复制相似问题