If the MyDate
column is a datetime
, as it appears to be, then it's already in the right "format". Don't convert it to a varchar(50)
in the predicate condition - this makes your query non-sargable and will kill performance on any indexes you might have.
Instead, take your parameters as date
or datetime
instances:
SELECT ...
FROM MyTable
WHERE MyDate >= @BeginDate
AND MyDate <= @EndDate
Your query should not depend on a specific date format in the input parameters - those parameters are not varchar
types, they are datetime
(or date
). When you run this query or stored procedure from whatever environment the application is in and supply binding parameters (you are using bind parameters, right?), said library will automatically handle any formatting issues.
If you try to use the >=
and <=
operators on character representations of dates, with any format other than the ISO standard yyyymmdd
, you will get the wrong results, because the alphabetical order is different from the temporal order. Don't do this.
If you simply need to write an ad-hoc query, i.e. this isn't being run from any programming environment, then simply do not use the dd/mm/yyyy
format. Use the ISO date format instead; it is unambiguous and implicitly convertible to datetime
values:
SELECT ...
FROM MyTable
WHERE MyDate >= '20091231'
AND MyDate <= '20100231'
Honestly, no other solution is acceptable in my mind. For ad-hoc queries, always use the unambiguous ISO standard for dates. For applications connecting to the database, always use bind parameters. If you're doing anything else, you're writing code that's either unreliable, insecure, or both.