How to get year, month and say out of SQL Date in SQL Server

How to get year, month and say 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

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *