views:

73

answers:

1

I have a query that takes too long to respond when the search parameter happens to be a varchar datatype with date. However, if i convert varchar to datetime variable, the query runs fine. For ex:

This takes too long.

select count(id)
  from names
 where updateddate > '1/5/2010'

This runs fine.

declare @dateparam datetime
    set @dateparam = convert(datetime, '1/5/2010',102)

select count(id)
  from names
 where updateddate > @dateparam

What's the reason one runs fine but the other doesn't?

+5  A: 

Because in the case of the varchar, it has to convert to date. This takes time, and may prevent the efficient use of indexes.

It's almost always best to use the correct type.

John Saunders