2016-03-03 78 views
0

我有一个存储过程要在一夜之间建立一个表。什么是重建表格时处理sql索引的最佳做法

第一步是截断,因为我不能保证现有记录不会被更新,因此擦除和重建是最简单的选择。

我希望得到的建议是索引的最佳实践。我应该在开始时放弃索引,然后再构建索引吗?或者有更好的方法。该表将在它周围300K记录,7列

+0

还有类似情况的另一个问题。参考: http://stackoverflow.com/questions/1983979/insertion-of-data-after-creating-index-on-empty-table-or-creating-unique-index-a –

+0

谢谢你的 – Matt

回答

1

这里有一些测试,它可以帮助您:

test1: 
1.truncate table and don't delete indexes 
2.insert data and check speed 
3.check fragmentation 

test2: 
1.Truncate table 
2.insert data and check speed 
3.create indexes and check fragmentation 


test1: 
--insert data and check speed 

delcare @id int=0 
select current_timestamp; 

while(@id<=1000000) 
begin 

insert into indextest 
select @id,newid(),case when @id%10=0 then 1 else @id end; 

set @[email protected]+1 
end 

select current_timestamp; 


--check fragmentation 
--now check fragmentation 
SELECT object_id, index_id, avg_fragmentation_in_percent, page_count 
FROM sys.dm_db_index_physical_stats(DB_ID(‘AdventureWorks2016’), OBJECT_ID(‘indextest’), NULL, NULL, NULL); 


test2: 
----truncate table 
truncate table indextest 

--drop indexes 
drop index idx_id on indextest; 
drop index nci_idx on indextest; 


---now insert data 
delcare @id int=0 
select current_timestamp; 

while(@id<=1000000) 
begin 

insert into indextest 
select @id,newid(),case when @id%10=0 then 1 else @id end; 

set @[email protected]+1 
end 

select current_timestamp; 

--create index 
create clustered index idx_id on indextest(id); 

create non clustered index nci_idx on indextest(addres); 

---check fragmentation: 
SELECT object_id, index_id, avg_fragmentation_in_percent, page_count 
FROM sys.dm_db_index_physical_stats(DB_ID(‘AdventureWorks2016’), OBJECT_ID(‘indextest’), NULL, NULL, NULL); 

摘要:
当索引已有

插入数据花费 3:23秒并且插入后碎片 enter image description here

当我们删除并重新加载数据后指标:

插入速度:** 2:44秒
**碎片:

enter image description here

这就是说,我的测试依赖于最佳日志增长设置,磁盘速度。此外,您可能不必担心碎片,碎片只会影响范围扫描。我建议根据您的表格使用情况删除并重新创建索引。

相关问题