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 FieldB
I want to switch the PK to be CLUSTERED, and the other index to be NONCLUSTERED.
I have to assume that the database will be in use at the moment I try to change the indexes round – so my primary concern that I want to avoid, is that at some point in the process the PK constraint will not exist on the table. I want to be protected against any risk of duplicate keys being inserted.
i.e. I can’t just drop the primary key and recreate it.
This process needs to be done via an SQL script, not via SSMS.
I have an approach which I think will work (I’ll post it as a potential answer), but would like to open it up in case I’m missing something or there is another/better way. Plus, it may prove useful for others in the future
1) Drop the existing clustered index first (IX_TableX_FieldB):
2) Create a (temporary) UNIQUE constraint on the unique fields referenced in the primary key
3) Drop the PRIMARY KEY
4) Recreate the PRIMARY KEY as CLUSTERED
5) Drop the temporary UNIQUE constraint
6) Add the IX_TableX_FieldB back on as NONCLUSTERED