From comment: 12/22/09
I discovered later on, this is actually a very BAD implementation. The reason is when using indexes, executing a function on each item requires an entire index scan to be done instead of an index seek. This completely screws up doing a range search for dates on a clustered index. Yikes.
The methods above work, but boy or they ever inefficient. Avoid them if at all possible. Consider using things like DateDiff(), etc.
And Remember, when your writing high performance queries always study the execution plan and reduce bottlenecks!
Why?
Sooner or later you will need to do date-only range searches (where you are not concerned with times). Many programmers will actually specify a start time of 12:00 AM and ending time of 11:59:59 PM to get around this. But if you write a lot of queries you will quickly find this to be an annoyance and without an appropriate solution it can be easy to forget about times all together; creating a hard to find bug that will crop up and have your users up in arms.
How?
Since datetimes are stored as binary values in SQL we can utilize this to our advantage by casting the datetime object to a decimal and passing that result to the floor() function to isolate the date and effectively chop off the time.
declare @startdate datetime
declare @enddate datetime
set @startdate = '01/01/2008'
set @enddate = '03/01/2008'
select
fname + ' ' + lname as emp_name,
convert(varchar(10), hire_date, 101) as hire_date,
hire_date as og_hire_date,
floor(cast(hire_date as decimal(9,4))) as og_hire_date_cast
from employees
where
floor(cast(hire_date as decimal(9,4))) between @startdate and @enddate
Note:
Conversely if we only wanted the time, we are concerned with what is on the right side of the decimal. Using the function makes this a cinch. For more information on how SQL stores datetimes internally, check out Date and Time (Transact-SQL) on MSDN
SQL Function, MSDN Ref.
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
CAST ( expression AS data_type [ (length ) ])
FLOOR ( numeric_expression )
Quick Tips
sql