Friday, March 1, 2013

How to get Year, Month and Day out of SQL Date in SQL Server

Let is say that we have the following Date 2007-04-05 10:13:14.109 and we want to get Year, Month and Day out of this date.

There is a function named DATEPART() that can be used to archive this.
DECLARE @MyDate AS DATETIME 
SET @MyDate = '2007-04-05 10:13:14.109'
SELECT DATEPART(DAY, @MyDate) AS MyDay, DATEPART(MONTH, @MyDate) AS MyMonth, DATEPART(YEAR, @MyDate) AS MyYear

The result would be:

MyYearMyMonthMyDay
20070405

Source: https://www.nilebits.com/blog/2011/07/how-to-get-year-month-and-say-out-of-sql-date-in-sql-server/