如何在 table 上删除聚簇索引(如果存在)并添加新的聚簇索引?

How to drop a Clustered Index on a table if it exists and add a new Clustered Index?

我正在 table 上创建聚簇索引,如果它已经存在则删除。

我正在使用这个查询。

DROP INDEX IF EXISTS CLX_Enrolment_StudentID_BatchID
ON Enrollment
CREATE INDEX CLX_Enrolment_StudentID_BatchID
ON Enrollment(Studentid, BatchId ASC);

现在,我想知道这里创建了哪个集群:- 这是集群还是非集群?

CREATE INDEX CLX_Enrolment_StudentID_BatchID
ON Enrollment(Studentid, BatchId ASC);

因为使用:-

DROP clustered INDEX IF EXISTS CLX_Enrolment_StudentID_BatchID
ON Enrollment 

我收到这个错误:-

Incorrect syntax near the keyword 'clustered'.

而且,如果我使用:-

DROP INDEX IF EXISTS CLX_Enrolment_StudentID_BatchID
ON Enrollment
go
CREATE clustered INDEX CLX_Enrolment_StudentID_BatchID
ON Enrollment(Studentid, BatchId ASC); 

我收到这个错误:-

Cannot create more than one clustered index on table 'Enrollment'. Drop the existing clustered index 'PK__enrollme__DE799CE1E4649295' before creating another.

现在,我想知道在我的第二个查询中创建了哪个索引。并且,如果正在创建两者的 none 那么如何删除聚簇索引(如果存在)并创建一个新的。

您可以尝试使用IF EXISTS语法检查sys.indexes table是否包含索引。

IF EXISTS(
    SELECT * 
    FROM sys.indexes 
    WHERE name='CLX_Enrolment_StudentID_BatchID' AND OBJECT_ID = OBJECT_ID('Enrollment')
)
BEGIN
    DROP INDEX CLX_Enrolment_StudentID_BatchID ON [dbo].[Enrollment]
END
GO

CREATE clustered INDEX CLX_Enrolment_StudentID_BatchID
ON Enrollment(Studentid, BatchId ASC); 

但我认为您的错误消息中的 table 上有一个索引 PK__enrollme__DE799CE1E4649295

修改

如果你想 DROP 自动 PK 或聚集索引,你可以尝试使用动态 sql 创建脚本并使用 sp_executesql 来执行它。

DECLARE @sql NVARCHAR(500),
        @TableName VARCHAR(50) = 'Enrollment',
        @Para NVARCHAR(500)='@TableName VARCHAR(50)'

SELECT @sql = CONCAT('ALTER TABLE ',@TableName,' DROP CONSTRAINT ',name)
FROM sys.indexes 
WHERE OBJECT_ID = OBJECT_ID(@TableName) AND type_desc = 'CLUSTERED' AND is_primary_key = 1
EXEC sp_executesql @sql,@Para,@TableName

SELECT @sql = CONCAT('DROP INDEX ',name,' ON dbo.',@TableName)
FROM sys.indexes 
WHERE OBJECT_ID = OBJECT_ID(@TableName) AND type_desc = 'CLUSTERED'

EXEC sp_executesql @sql,@Para,@TableName

if your table already contains PK you need to use ALTER TABLE .... DROP CONSTRAINT instead of drop index.