Your query is essentially:
select @VisitedOutlets= count(distinct CustomerId)
from dbo.VisitDetail
where RouteId = @intRouteID and
CONVERT(VARCHAR(10), VisitDate, 111) between
CONVERT(VARCHAR(10), @FromDate, 111) and CONVERT(VARCHAR(10), @ToDate, 111);
I think this query can be optimized to take advantage of indexes. One major problem is the date comparison. You should not be doing any conversion for the comparison on VisitDate
. So, I would rewrite the query as:
select @VisitedOutlets= count(distinct CustomerId)
from dbo.VisitDetail vd
where vd.RouteId = @intRouteID and
vd.VisitDate >= cast(@FromDate as date) and
vd.VisitDate < dateadd(day, 1, cast(@ToDate as date))
For this query, you want an index on VisitDetail(RouteId, VisitDate, CustomerId)
. I would also store the constants in the appropriate format, so conversions are not needed in the query itself.
between
is dangerous when using dates. Here is an interesting discussion on the topic by Aaron Bertrand.