改变sql中的聚簇索引

时间:2018-04-03 08:53:44

标签: sql sql-server

如何更改PK上的聚簇索引以更改索引列或包含额外列?

我是否使用create index

删除并创建
CREATE CLUSTERED INDEX dateQ ON dbo.devTable(DateCreated, Id)

点击SSMS上的drop and create吐出以下内容。我不知道with参数内发生了什么。我想将datecreated包含在我的索引中。

USE [devDb]
GO

ALTER TABLE [dbo].[devTable] DROP CONSTRAINT 
[PK__devTab__3214EC07339391EF] WITH ( ONLINE = OFF )
GO

SET ANSI_PADDING ON
GO

ALTER TABLE [dbo].[devTable] ADD PRIMARY KEY CLUSTERED 
(
 [DateCreated] ASC, //I want to add date created to the index
 [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, 
IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = 
ON) ON [PRIMARY]
GO

1 个答案:

答案 0 :(得分:0)

好的,下面的示例脚本可以帮助您。

USE Sandbox;
GO
--Very simple sample table
CREATE TABLE IndexSample (ID int IDENTITY(1,1),
                          DateCreated date,
                          CONSTRAINT PK_ID PRIMARY KEY CLUSTERED (ID ASC));
GO

--You can only have one CLUSTERED INDEX on a table. As you've declared the ID as CLUSTERED PRIMARY KEY you'll need to drop it
--Note that if this key is referenced anywhere eklse, you'll need to drop those keys as well.
ALTER TABLE IndexSample DROP CONSTRAINT PK_ID;

GO
--Now, we need to recreate the PRIMARY KEY, but not CLUSTER it.
ALTER TABLE IndexSample ADD CONSTRAINT PK_ID PRIMARY KEY NONCLUSTERED (ID ASC);
--Then create your other Foreign keys and constraints again
GO
--Now create your Clsutered index
CREATE CLUSTERED INDEX DateCreated_ID ON IndexSample (DateCreated ASC, ID ASC);

GO
--Clean up
DROP TABLE IndexSample;

正如我在评论中指出的那样,您需要DROP现有的约束,因为您可以" #cluster" INDEX。删除后,您可以创建新的NONCLUSTERED PRIMARY KEY。最后,您添加新的CLUSTERED索引。