Strangenut

How to select only the date part of a datetime field in SQL (SQL Server 2000/2005/2008)

Have you ever needed to get only the date part out of a datetime field in SQL and wanted to drop the precision of the timepart?  It's actually surprisingly easy, and with this method is pretty fast as well. I've had to do this many times but always forget the syntax in T-SQL (though this should also work on other database platforms as well) so I figured I would put it up here on the blog and hopefully it would come in handy for some of you guys as well!

 

SELECT (CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)) AS CurrentDate

 

You can, of couse, replace the call to getdate() with a column from a table that you are selecting from and it will work just as well.  The performance hit for using this method is neglible ... especially considering the alternative of casting the calling YEAR(), MONTH() and DAY() on the field and concatenating them back together as strings.

 

 


Posted Jan 28 2010, 11:19 PM by dacrowlah
Filed under: , ,
Powered by Community Server (Non-Commercial Edition), by Telligent Systems