How can I compare only the time portion of a DateTime data type in SQL Server 2005? For example, I want to get all records in which MyDateField is after a specific time. The
Others have posted alternative methods of forming the query, but I want to respond to something you say in the first paragraph:
The following example is a very long and probably not fast way of doing this.
Performance-wise, it doesn't really matter if you have one DATEPART
or 10 DATEPARTS
in there; the fact that you have even one DATEPART
is what's going to hurt performance.
If you need to compare on time but not date, then Lasse's comment is right on the money - you need to normalize into separate date/time columns. In fact, SQL 2008 introduces date
and time
types and recommends that you use them instead of datetime
. You don't have this in SQL 2005, but you can work around it with, say, a ticks field for time-of-day, and a check constraint that forces all the dateparts of the date column to zero.
If you later need to perform filters on the full date+time, it is easy to create a computed column, and if performance is an issue for those, you can persist that column and create an index on it.