Sql-Server

在不刪除主鍵的情況下更改聚集索引

  • July 17, 2019

過去,我選擇在表中創建datetime的列作為不適當的聚集索引。

現在我得出結論(基於執行計劃),最好選擇 ID身份主鍵作為聚集鍵,因為它經常被作為外鍵引用。

我想刪除目前的聚集鍵並創建一個新的,但我不能刪除主鍵,因為full-text索引依賴於該主鍵。

我可以將主鍵切換到聚集索引還是需要刪除主鍵和所有依賴對象的鏈?

下面您將找到表定義和聚集索引定義。

CREATE TABLE [dbo].[Realty](
   [Id] [int] IDENTITY(1,1) NOT NULL,  
   [Created] [datetime] NOT NULL,
   ....

CONSTRAINT [PK_Realty] PRIMARY KEY NONCLUSTERED 
(
   [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
...


CREATE CLUSTERED INDEX [Created] ON [dbo].[Realty]
(
   [Created] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
GO

ID只需刪除現有的聚集索引,然後在列上創建一個新的。

DROP INDEX [Created] ON dbo.Realty;
GO

CREATE UNIQUE CLUSTERED INDEX CX_Realty ON dbo.Realty (ID);
GO

當然,您需要在維護視窗期間執行此操作,以免造成太多阻塞。如果您有企業版,您可以通過添加WITH (ONLINE=ON)到語句來線上執行 CREATE INDEX 操作。

引用自:https://dba.stackexchange.com/questions/117079