I have used below query in one of my stored procedures
SELECT officeid, rdate
FROM dbo.mytable
Where OfficeID = OfficeID
AND YEAR(h.rDate) = @year
AND MONTH(h.rDate) BETWEEN 1 AND 4
The above query fails to be a SARG ( Search Argument) due to the usage of fuctions MONTH and YEAR in Where clause. This leads Index scan during stored procedure execution. Is there any way to rewrite the above query to handle the above logic (without function)
(P.S: rdate is datetime datetype and @year is INT datatype)
Use Pseudo values..
This below function is SARGABLE(but will be lengthy) ,since CAST( DATETIME to DATE) is SARAGABLE,So Index will be used .
Example:
Cast(h.rDate as DATE)
between datefromparts(@year,01,01)
and datefromparts(@year,04,30)
Use date range comparisons. For example,
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With