为什么使用非聚集索引而不是聚簇索引

时间:2015-08-23 12:19:13

标签: sql-server sql-server-2008

我有一个存储过程。如果我使用where(@detailId为null或SalesOrderDetailID = @detailId),则使用非聚集索引,但如果我将where子句更改为SalesOrderDetailID = @detailId,则使用clusted index。

检查以下存储过程。主键是列的组合 - (SalesOrderID,SalesOrderDetail)。

alter procedure samproc

@detailId int = null

with recompile
as
begin

select SalesOrderID 
from sales.SalesOrderDetail 
where  (@detailId is null or SalesOrderDetailID = @detailId)

end
go

exec dbo.samproc @detailId = 1

问题 - 当我在where子句中使用或条件时,为什么不使用聚簇索引。我需要使用或者因为想要跳过where条件,如果没有传递参数。我也使用

where isnull(@detailId,SalesOrderDetailID)

但是在实际场景中我有10个参数,这可能很昂贵,因为不会使用isnull函数内的列索引,其次是isnull导致表扫描。这就是我使用

的原因
where  (@detailId is null or SalesOrderDetailID = @detailId)

有人可以告诉我如何避免非聚集索引并使用聚集索引。

1 个答案:

答案 0 :(得分:1)

使用$finalJSON["items"] = array(); //old syntax 的索引使用很麻烦。最好的办法是构造一个动态SQL语句并执行:

echo json_encode($finalJSON);

注意:您应该使用参数执行此操作。 。

or

结果将是一个更简单的语句,可以更好地利用索引。