Change a Primary Key from Nonclustered to Clustered

前端 未结 3 609
闹比i
闹比i 2020-12-23 12:02

Suppose I have an SQL Server 2005 table, TableX, with 2 indexes on it:

PK_TableX = PRIMARY KEY NONCLUSTERED on FieldA
IX_TableX_FieldB = CLUSTERED on Fiel

3条回答
  •  萌比男神i
    2020-12-23 12:28

    1) Drop the existing clustered index first (IX_TableX_FieldB):

       DROP INDEX TableX.IX_TableX_FieldB
    

    2) Create a (temporary) UNIQUE constraint on the unique fields referenced in the primary key

        ALTER TABLE TableX
        ADD CONSTRAINT UQ_TableX UNIQUE(FieldA)
    

    3) Drop the PRIMARY KEY

        ALTER TABLE TableX
        DROP CONSTRAINT PK_TableX
    

    4) Recreate the PRIMARY KEY as CLUSTERED

       ALTER TABLE TableX
       ADD CONSTRAINT PK_TableX PRIMARY KEY CLUSTERED(FieldA)
    

    5) Drop the temporary UNIQUE constraint

       ALTER TABLE TableX
       DROP CONSTRAINT UQ_TableX
    

    6) Add the IX_TableX_FieldB back on as NONCLUSTERED

       CREATE NONCLUSTERED INDEX IX_TableX_FieldB ON TableX(FieldB)
    

提交回复
热议问题