Answers:
在SQL Server中,总是将聚簇索引键列添加到非聚簇索引中以充当行定位器(请参阅:有关非聚簇索引键的更多信息)。
对于声明为唯一的NCI,将它们添加为包含列,否则将它们添加到密钥的末尾。
如果默认位置对于您的查询而言不是最佳的,则可能需要显式添加列。例如,如果要控制ASC
/ DESC
方向,或者要控制索引中键列的位置。
CREATE TABLE T
(
A INT,
B INT,
C INT ,
PRIMARY KEY CLUSTERED (B DESC, C DESC)
)
/*Implicitly adds B DESC, C DESC to end of key*/
CREATE NONCLUSTERED INDEX ix1 ON T(A ASC)
/*No sort operation*/
SELECT *
FROM T
ORDER BY A ASC,B DESC, C DESC
/*
But the avove index won't be able to seek into A,C
and will need a residual predicate after seeking into A.
For the following query
*/
SELECT *
FROM T
WHERE A=1 AND C > 4
ORDER BY C ASC, B DESC
/*This index explicitly controlling the key column position
and direction would be better*/
CREATE NONCLUSTERED INDEX ix2 ON T(A ASC, C ASC, B DESC)