我想提高查询的性能,该查询确实有一个带有非确定性函数调用的 where 子句。
Select Count(*)
From table1
Where DateDiff(month, Cast(table1.Date As DateTime), GetDate()) = 0
我认为这个问题对于连接同样有效:
Select table1.column1
From table1 Inner Join table2
On table1.MonthOfHappyness =
DateDiff(month, Cast(table2.SomeDate As DateTime), GetDate())
自
DateDiff(month, Cast(adrPkt.PktRevDato As DateTime), GetDate())
是不确定的 我无法创建带有计算列的 View 并对其建立索引。 请参阅:SQL Server (2005) - "Deleted On" DATETIME and Indexing
我有什么选择可以提高性能?
最佳答案
除了非确定性函数之外,我看到的问题是您在字段上进行计算。这(通常)使得该字段上的任何索引都无法被查询使用。
此链接的第二段 ( Ten Common SQL Programming Mistakes (Functions on indexed columns in predicates) ) 提供了有关何时发生这种情况、如何避免这种情况以及有时优化器如何在使用函数的情况下使用索引的更详细信息。
简而言之,通常可以通过保持字段完整(不对其进行任何计算)来更改查询,而不是依赖改进的优化器,而是对其他值进行(反向)计算。在您的情况下为 GetDate()
提供的当前日期。那么查询就可以使用字段table1.Date
的索引了。
所以,你可以使用类似的东西:
SELECT COUNT(*)
FROM table1
WHERE table1.Date
BETWEEN
/* First Day of Current Month */
AND
/* Last Day of Current Month */
您只需要找到可以获取当月第一天和最后一天的函数。
这篇博文可以帮助您: sql-server-query-to-find-first-and-last-day-of-current-month/
更好的是,这个 StackOverflow 问题/答案: simplest-way-to-create-a-date-that-is-the-first-day-of-the-month-given-another-date
我必须进行测试,但我认为上述内容的细微变化就可以了:
SELECT COUNT(*)
FROM table1
WHERE table1.Date
>= /* First Day of Current Month */
DATEADD(mm, DATEDIFF(mm, 0, GetDate() ), 0)
AND table1.Date
< /* First Day of Next Month */
DATEADD(mm, 1 + DATEDIFF(mm, 0, GetDate() ), 0)
关于sql-server - 如何提高 where 子句或联接中列的非确定性函数的性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6233319/