Best way to change clustered index (PK) in SQL 2005

后端 未结 4 789
北海茫月
北海茫月 2021-01-02 23:37

I have a table which has a clustered index on two columns - the primary key for the table. It is defined as follows:

ALTER TABLE Table ADD  CONSTRAINT [PK_T         


        
相关标签:
4条回答
  • 2021-01-03 00:15

    This isn't a complete answer to your question, but make sure that if you have any other indexes on the table that you drop those first. Otherwise SQL Server will have to rebuild them all when you remove the clustered index then rebuild them all again when you add back a new clustered index. The usual steps are:

    1. Remove all non-clustered indexes
    2. Remove clustered index
    3. Add new clustered index
    4. Add back all non-clustered indexes
    0 讨论(0)
  • 2021-01-03 00:29

    Clustered indexes don't actually change the physical order of the data being stored in the table it self. It hasn't been this way since SQL 6.5.

    The data on the pages is stored in the correct order. The pages can be stored on the disk in any physical order.

    0 讨论(0)
  • 2021-01-03 00:30
    1. Create a new table:

      CREATE TABLE newtable (colA INT, colB INT)
      
      • Insert all values from the old table into the new table:

        INSERT INTO newtable SELECT * FROM table

      • Drop the old table:

        DROP TABLE table

      • Rename the new table to the old table

        EXEC sp_rename 'newtable', 'table'

      • Build the indexes:

        ALTER TABLE Table ADD CONSTRAINT PK_Table PRIMARY KEY NONCLUSTERED ( ColA, ColB ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

    0 讨论(0)
  • 2021-01-03 00:39

    If your table is getting up to 1 TB in size and probably has LOTS of rows in it, I would strongly recommend NOT making the clustered index that much fatter!

    First of all, dropping and recreating the clustered index will shuffle around ALL your data at least once - that alone will take ages.

    Secondly, the big compound clustered index you're trying to create will significantly increase the size of all your non-clustered indices (since they contain the whole clustered index value on each leaf node, for the bookmark lookups).

    The question is more: why are you trying to do this?? Couldn't you just add another non-clustered index with those columns, to potentially cover your queries? Why does this have to be the clustered index?? I don't see any advantage in that....

    For more information on indexing and especially the clustered index debate, see Kimberly Tripp's blog on SQL Server indexes - very helpful!

    Marc

    0 讨论(0)
提交回复
热议问题