posted 2/28/2010 by MikeMollenhour - Views: [5045]
I was at a client’s site recently discussing the benefits of dropping an index and rebuilding at the end of a large batch (SQL 2005 or SQL 2008). There are several things I have learned in my career but one of the most important things has been to try to eliminate hard coding and the old keep it simple technique. So say I have 4 procs that I am using to insert into the same table and I decided for better performance I will drop the index and recreate it at the end of my load. Does anyone else see the issue with this? Here is an example of drop/create index:
---First Drop index before load
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[myTable]') AND name = N'ix_MyTableIndex')DROP INDEX [ix_MyTableIndex] ON [dbo].[myTable] WITH ( ONLINE = OFF )GO
--Load Data
Insert into MyTable....
--Recreate Index
CREATE NONCLUSTERED INDEX [ix_MyTableIndex] ON [dbo].[myTable] ( [ContactID] ASC, [NameStyle] ASC, [Title] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]GO
So you may say "Mike what’s wrong with that" Until SQL 2005 this was the way I always did it as well... Along comes SQL 2005 and Alter Index disable:
First disable index
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[myTable]') AND name = N'ix_MyTableIndex')ALTER INDEX ix_MyTableIndex ON [MyTable] DISABLEGO
ALTER INDEX ix_MyTableIndex ON [MyTable] REBUILD PARTITION = ALL GO
So the advantage with the last code is all the metadata about the index still persists in SQL. So now if I as a DBA were to add a column to this index I have two choices use the first code snippet and hope that I have edited the metadata of creating the index in all 4 procs so I don't get a surprise of this column dropping off the index after load. Or I can use the new disable index to my advantage and no worries the metadata I have changed stays persisted! I know which one I am going to use.