Myth #29: You can defragment the heap after you drop the heap by a clustered index
NOOOOOOOOOOOOO!!!
To heap a clustered index and drop it seems to me to be the top 2 in addition to shrinking the database.
If you see fragments on the heap through sys.dm_db_index_physical_stats (or an older version of DBCC SHOWCONTIG), do not defragment the heap by creating a clustered index and then deleting the clustered index. A good practice should be to set up a clustered index and not delete it, and there is already a lot of information on how to choose an ideal clustered index key--narrow, rarely changed, unique, self increasing. Kimberly has an article summarizing this: ever-increasing clustering key-the Clustered Index debate..........again! (Note that this is based on the SQL Server 2005 version), I also have an example: an example of a nasty cluster key.
You can also pass alter TABLE in SQL Server 2008 ... Rebuild to clear heap fragments, but this practice and the establishment of a clustered index after the deletion of the same evil.
If you want to ask, why do I have an obsession with this? Well, let me explain: each row in a nonclustered index points to a link to a RID or a clustered index key (for more information: What happens if I Drop a Clustered index?), this link appears in one of the following two ways:
If the table in which the clustered index is located is a heap, then the link is a RID.
If the table in which the clustered index is located is a clustered index, then the link is the clustered index key.
If you want to know more about this, see the link at the bottom of the article.
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/database/SQLServer/
So it's not hard to see that if you want to turn the heap into a clustered index, then all the rids of the nonclustered index are invalidated, so all nonclustered indexes need to be rebuilt. Similarly, if you delete a clustered index key, all clustered index keys stored on all nonclustered indexes will fail, and therefore all nonclustered indexes need to be rebuilt.
Simply put, if you create and then delete the clustered index, all nonclustered indexes will be rebuilt two times.
If you are using ALTER TABLE of SQL Server 2008 ... Rebuild to defragment the heap, you also need to rebuild all nonclustered indexes because all the rids will change.
So what about "rebuilding" a clustered index? This depends on the version of SQL Server and whether you are indexing the rebuild or changing the index. A common misconception is that partitioning a table will change the clustered index key, but not in fact. For those operations that cause nonclustered index rebuilds, see the following list: Indexes from Every angle:what happens to non-clustered Indexes when the table structure is Chang Ed?.