从Sql server中的where子句中排除函数

时间:2016-07-13 13:31:06

标签: sql sql-server tsql stored-procedures sql-server-2012

我在query

中使用了stored procedures以下SELECT officeid, rdate FROM dbo.mytable Where OfficeID = OfficeID AND YEAR(h.rDate) = @year AND MONTH(h.rDate) BETWEEN 1 AND 4
SARG ( Search Argument)

由于在MONTH中使用了功能YEARWhere clause,上述查询无法成为Index scan。在stored procedure执行期间,这会导致function。有没有办法重写上述查询来处理上述逻辑(没有rdate

(P.S:datetime@year日期类型,INTlet compile_lib = lib_array.map((item) => { return new Promise((resolve, reject) => { compileEntry(item); }) }); 数据类型)

2 个答案:

答案 0 :(得分:5)

使用伪值..

以下这个函数是SARGABLE(但会很长),因为 CAST( DATETIME to DATE) is SARAGABLE ,所以将使用索引。

示例:

Cast(h.rDate as DATE) 
between datefromparts(@year,01,01) 
 and datefromparts(@year,04,30)

答案 1 :(得分:2)

使用日期范围比较。例如,

 SELECT officeid, rdate
    FROM dbo.mytable
    Where OfficeID   = OfficeID
    --Filter by dates that are between January 1st, midnight, inclusive, and
    --May 1st, exclusive, in the desired year
    AND h.rDate >= Convert(DateTime,'1/1/' + Convert(VarChar(4),@year))
    AND h.rDate < Convert(DateTime,'5/1/' + Convert(VarChar(4),@year))