2017-09-25 71 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秒的查询,所以学到了很酷的东西。 –