06 January 2008

How do I select only the date from a datetime data type?

Selecting only the date portion from a datetime data type could be accomplished in a number of ways. One of the most convenient methods is to simply use CONVERT and one of the many style values.

SELECT GETDATE() AS MyDate
returns the default format:

MyDate
-----------------------
2008-01-06 19:39:15.410

However, buy using CONVERT and applying a particular style value, we are able to achieve the desired result. For example:

SELECT CONVERT(VARCHAR(10),GETDATE(),126) AS MyDate
returns:

MyDate
----------
2008-01-06

Another style example:

SELECT CONVERT(VARCHAR(10),GETDATE(),101) AS MyDate
returns:

MyDate
----------
01/06/2008

For additional information, visit: http://msdn2.microsoft.com/en-us/library/aa226054(SQL.80).aspx

No comments: