Sql server 如何通过索引优化SQL Server 2012中的视图性能
我有这样的看法:Sql server 如何通过索引优化SQL Server 2012中的视图性能,sql-server,Sql Server,我有这样的看法: create view dbo.VEmployeeSalesOrders as select employees.employeeID, Products.productID, Sum(Price * Quantity) as Total, salesDate, COUNT_BIG() as [RecordCount] from dbo.Employees inner join
create view dbo.VEmployeeSalesOrders
as
select
employees.employeeID, Products.productID,
Sum(Price * Quantity) as Total,
salesDate,
COUNT_BIG() as [RecordCount]
from
dbo.Employees
inner join
dbo.sales on employees.employeeID = sales.employeeID
inner join
dbo.products on sales.productID = products.ProductID
group by
Employees.employeeID, products.ProductID, salesDate
当我从dbo.vemployeesalesforders中选择*时,它将占用执行计划的97%。它需要更快
当我尝试创建索引时,会触发一个异常,并显示以下消息:
选择列表未包括对计数的正确使用\u Big()
为什么会出现此错误?1-首先,您需要更改视图并使其包含COUNT\u BIG()函数,因为您在select Station中使用了聚合函数,
使用它的原因是SQL Server需要跟踪记录所在的位置、记录数
像这样
create view dbo.VEmployeeSalesOrders
as
select employees.employeeID,Products.productID,Sum(Price*Quantity)
as Total,salesDate,COUNT_BIG(*) as [RecordCount]
from dbo.Employees
inner join dbo.sales on employees.employeeID=sales.employeeID
inner join dbo.products on sales.productID-products.ProductID
group by Employees.employeeID,products.ProductID,salesDate
2-然后你需要创建这样的索引
Create Unique Clustered Index Cidx_IndexName
on dbo.VEmployeeSalesOrders(employedID,ProductID,SalesDate)
希望它能工作除此之外,在查询索引视图时,您必须使用(NOEXPAND)
添加提示<例如,code>SELECT*FROM dbo.veEmployeeSalesOrders WITH(NOEXPAND)
。@EvaldasBuinauskas,只想补充一点,SQL Server企业版和开发者版中不需要WITH(NOEXPAND)
提示。这些版本中的优化器将自动考虑视图上的索引,即使在直接从基础表中选择时也不需要使用(No展开)作为索引来考虑视图。automatically@Anas萨阿德感谢它的工作和执行计划,它需要3%,我大different@Darknight,请注意,如果未按中所述正确设置“magic 7”连接设置,则修改基础表的应用程序将出错。如果97%是查询计划中的百分比,请记住这是一个估计值,可能是完全错误的。