当你执行
ALTER TABLE someTable ADD CONSTRAINT PK_someTable PRIMARY KEY (id);
如果没有聚集索引,someTable
则 PK 将是聚集 PK。否则,如果在执行前有聚集索引ALTER .. ADD ... PRIMARY KEY (id)
的 PK 将是非聚集 PK。
-- 测试#1
BEGIN TRAN;
CREATE TABLE dbo.MyTable
(
id INT NOT NULL,
Col1 INT NOT NULL,
Col2 VARCHAR(50) NOT NULL
);
SELECT i.name, i.index_id, i.type_desc
FROM sys.indexes i
WHERE i.object_id = OBJECT_ID(N'dbo.MyTable');
/*
name index_id type_desc
---- ----------- ---------
NULL 0 HEAP
*/
ALTER TABLE dbo.MyTable
ADD CONSTRAINT PK_MyTable PRIMARY KEY (id);
SELECT i.name, i.index_id, i.type_desc
FROM sys.indexes i
WHERE i.object_id = OBJECT_ID(N'dbo.MyTable');
/*
name index_id type_desc
----------- ----------- ---------
PK_MyTable 1 CLUSTERED
*/
ROLLBACK;
-- 测试#2
BEGIN TRAN;
CREATE TABLE dbo.MyTable
(
id INT NOT NULL,
Col1 INT NOT NULL,
Col2 VARCHAR(50) NOT NULL
);
SELECT i.name, i.index_id, i.type_desc FROM sys.indexes i WHERE i.object_id = OBJECT_ID(N'dbo.MyTable');
/*
name index_id type_desc
---- ----------- ---------
NULL 0 HEAP
*/
CREATE CLUSTERED INDEX ix1
ON dbo.MyTable(Col1);
SELECT i.name, i.index_id, i.type_desc FROM sys.indexes i WHERE i.object_id = OBJECT_ID(N'dbo.MyTable');
/*
name index_id type_desc
---- ----------- ---------
ix1 1 CLUSTERED
*/
ALTER TABLE dbo.MyTable
ADD CONSTRAINT PK_MyTable PRIMARY KEY (id);
SELECT i.name, i.index_id, i.type_desc FROM sys.indexes i WHERE i.object_id = OBJECT_ID(N'dbo.MyTable');
/*
name index_id type_desc
---------- ----------- ------------
ix1 1 CLUSTERED
PK_MyTable 2 NONCLUSTERED
*/
ROLLBACK;