How to get only DATE portion out of DATETIME column in MSSQL ?
Ayende just posted a T-SQL function that strips DATE from DATETIME value. Since I like T-SQL for this kind of tricks I just decided to post kinda the same snippet just make it more simple. Enjoy :)
It has some disadvantages. The biggest disadvantage is that you have implicit conversion from VARCHAR to DATETIME - so pay attention you can get a different date than the one you are working with.
I was sure that this method is 100% accurate. Result of CONVERT(varchar(8), GETDATE(), 112) should be treated equally on all versions of SQL Server with any localization. Date format of 'yyyymmdd' is Microsoft's recommended way of representing date as a string. So i thought. Can you give an example when this method will not work as intented?
hm... Actually this way is ok. It is also a docummented one, but...
I don't like it because IMHO it just can not be a good way to convert datetime to a string and convert it back just to get datetime. You have one explicit conversion and one implicit which is especially not good for SQL.
Implicit conversion takes place here:
@date = VARCHAR
Actually my way is also a bit more performant. But conversion will be a pain in queries (WHERE clause, GROUP BY clause, etc)
MSSQL 2008 introduces several new DATETIME datatypes for T-SQL: TIME, DATE, DATETIME2, DATETIMEOFFSET. It is obvious that TIME and DATE provide the ability to store separately DATE and TIME parts of DATETIME. It was not possible to do in previous versions of MSSQL, however [ ... ]