我有一个从Delphi应用程序运行的查询,它在上周完全运行数月后突然开始计时.更进一步,当它运行时,它会使服务器变慢,导致其他用户认为系统崩溃
从Management Studio运行我在旋转超过5分钟后停止查询
服务器ID SqlExpress 2008 R2
现在有问题的查询
SELECT *
FROM SignelOutilsListeJobs_View4
WHERE (CreatedDate > (GETDATE() - 365))
这里有趣的是所需的时间和当我改变返回的天数时,行返回.活动监视器似乎没有显示超过查询正在运行
SELECT *
FROM SignelOutilsListeJobs_View4 -- 00.00.02 38882 ROWS
SELECT *
FROM SignelOutilsListeJobs_View4
WHERE (CreatedDate > (GETDATE() - 600)) -- 00.00.02 16217 ROWS
SELECT *
FROM SignelOutilsListeJobs_View4
WHERE (CreatedDate > (GETDATE() - 500)) -- 00.00.02 13013 ROWS
SELECT *
FROM SignelOutilsListeJobs_View4
WHERE (CreatedDate > (GETDATE() - 200)) -- 00.00.12 4118 ROWS
所以我想知道这里发生了什么?有任何想法吗?
谢谢
最佳答案 从 GETDATE (Transact-SQL)开始:
Using SWITCHOFFSET with the function GETDATE() can cause the query to run slowly because the query optimizer is unable to obtain accurate cardinality estimates for the GETDATE value. We recommend that you precompute the GETDATE value and then specify that value in the query as shown in the following example. In addition, use the OPTION (RECOMPILE) query hint to force the query optimizer to recompile a query plan the next time the same query is executed. The optimizer will then have accurate cardinality estimates for GETDATE() and will produce a more efficient query plan.
换句话说,您可以尝试编辑查询,如下所示:
SELECT *
FROM SignelOutilsListeJobs_View4
WHERE CreatedDate > (GETDATE() - 200) OPTION (RECOMPILE)
作为上述替代方法,您可以考虑在视图上创建唯一的聚簇索引:
CREATE UNIQUE CLUSTERED INDEX SignelOutilsListeJobs_unique_index1
ON SignelOutilsListeJobs_View4 (CreatedDate, <some unique key>)
来自Microsoft TechNet:
> Designing Indexed Views
> Improving Performance with SQL Server 2008 Indexed Views
> Optimizing Queries That Access Correlated datetime Columns