在上篇文章里,我讨论了唯一和非唯一聚集索引的区别。我们已经知道,SQL Server内部使用4 bytes的uniquifier来保证非唯一聚集索引行唯一。今天我们来看下唯一聚集索引上,唯一和非唯一非聚集索引的区别。当我们在表上定义PRIMARY KEY约束时,SQL Serve ...
在上篇文章里,我讨论了唯一和非唯一聚集索引的区别。我们已经知道,SQL Server内部使用4 bytes的uniquifier来保证非唯一聚集索引行唯一。今天我们来看下唯一聚集索引上,唯一和非唯一非聚集索引的区别。当我们在表上定义PRIMARY KEY约束时,SQL Server会为我们创建唯一聚集索引;另外我们可以通过CREATE UNIQUE CLUSTERED INDEX语句在表上创建唯一聚集索引。下面的代码会创建customers表,然后在它上面创建唯一聚集索引,最后在表上创建唯一和非唯一非聚集索引。
1 -- Create a table with 393 length + 7 bytes overhead = 400 bytes 2 -- Therefore 20 records can be stored on one page (8.096 / 400) = 20,24 3 CREATE TABLE Customers 4 ( 5 CustomerID INT NOT NULL, 6 CustomerName CHAR(100) NOT NULL, 7 CustomerAddress CHAR(100) NOT NULL, 8 Comments CHAR(189) NOT NULL 9 ) 10 GO11 12 -- Create a unique clustered index on the previous created table 13 CREATE UNIQUE CLUSTERED INDEX idx_Customers ON Customers(CustomerID) 14 GO 15 -- Insert 80.000 records 16 DECLARE @i INT = 1 17 WHILE (@i <= 80000) 18 BEGIN 19 INSERT INTO Customers VALUES 20 ( 21 @i, 22 'CustomerName' + CAST(@i AS CHAR), 23 'CustomerAddress' + CAST(@i AS CHAR), 24 'Comments' + CAST(@i AS CHAR) 25 ) 26 SET @i += 1 27 END 28 GO29 30 -- Create a unique non clustered index on the clustered table 31 CREATE UNIQUE NONCLUSTERED INDEX idx_UniqueNCI_CustomerID 32 ON Customers(CustomerName) 33 GO 34 35 -- Create a non-unique non clustered index on the clustered table 36 CREATE NONCLUSTERED INDEX idx_NonUniqueNCI_CustomerID 37 ON Customers(CustomerName) 38 GO
原标题:索引键的唯一性(3/4):唯一聚集索引上的唯一和非唯一非聚集索引
关键词:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。