2017-09-25 104 views
1

我期待在與查詢,爲where子句,DateDiff(month, table1.dateReported, table2.dateTransDate) <= 6,其中dateReported和dateTransdate在不同的表的一部分。我最近讀到在where子句中使用SQL函數會導致性能問題。我怎樣才能改變這個不使用datediff?在SQL Server消除DateDiff的where子句

它基本上與一些照片喜歡

SELECT * 
FROM Table1 
LEFT JOIN Table2 on Table1.transactionID = Table2.transactionID 
WHERE DateDiff(month, Table1.dateReported, Table2 .dateTransDate) <= 6 
+0

不會是你最關心的,你爲什麼不使用構建功能如果他們已經指出你的快捷方式的xD – LONG

+1

是否datereported,並在同一個表或不同的表datetransdate?如果相同,它不會是sargable(至少不創建一個自定義計算列)如果分開,你可以使它對一列而不是另一列是sargable。哪個最好取決於。 –

+0

請在您的問題中包含您已有的查詢。從哪個表中清除DateDiff表達式中的列來自哪個表。 –

回答

3

您可以使用

WHERE Table1.dateReported >= 
    /*First day of the month six months previous to Table2.dateTransDate*/ 
    DATEADD(month, -6 + DATEDIFF(month, 0, Table2.dateTransDate), 0) 

潛在允許在Table1.transactionID, Table1.dateReported的索引使用。

或者

Table2.dateTransDate <= 
    /*Last day of the month six months after Table1.dateReported*/ 
    DATEADD(DAY,-1,DATEADD(month, 7 + DATEDIFF(month, 0, Table1.dateReported), 0)) 

以潛在地允許在Table2.transactionID, Table2.dateTransDate的索引使用。

A test rig is here to validate it for a cross joined year of dates to ensure all three return the same results

+0

這看起來似乎削減了約1秒的查詢,所以學到了很酷的東西。 –