DATEPART Function in SQL Server

In this article, I would like to show the Datepart Function in SQL Server. The Datepart Function is a built-in function. The Datepart Function returns a portion or single part of an SQL Server Datetime field. So let's have a look at a practical example of how to use a Datepart Function in SQL Server 2012. The example is developed in SQL Server 2012 using the SQL Server Management Studio.

The Datepart Function

The SQL Server Datepart function returns a portion of an SQL Server Datetime field.

Syntax

The syntax of the Datepart built-in date function is as follows.

DATEPART ([Date part], [Datetime])

Here, the <Date part> parameter is the part of the datetime. DateTime is the name of a SQL Server Datetime field and a portion is one of the following

Ms   Milliseconds
Yy   Year
Qq   Quarter of the Year
Mm   Month
Dy   The Day of the Year
Dd   Day of the Month
Wk   Week
Dw   The Day of the Week
Hh   Hour
Mi   Minute
Ss   Second

Example 1

Select getdate() as CurrentDate
Go

Select datepart(Yy, getdate()) As Year
Go

Select datepart(Mm, getdate()) As Month
Go

Select datepart(Dd, getdate()) As DayOfMonth
Go

Select datepart(Wk, getdate()) As Week
Go

Select datepart(Dw, getdate()) As [Day of the Week]
Go

Select datepart(Dy, getdate()) As [Day of the Year]
Go

Select datepart(Hh, getdate()) As Hour
Go

Select datepart(Mi, getdate()) As Minute
Go

Select datepart(Ss, getdate()) As Second

Output

Datepart-Function-in-SQL-Server.jpg

Example 2

Now I want to check that the date was in AM or PM with the Datepart function.

Select getdate() as CurrentDate
Go

Select 
    case
        when datepart(hour, getdate()) < 12 then 'It''s AM'
        else 'It''s PM'
    end as [Date]

Output

Datepart-Function-with-am-and-pm-in-SQL-Server.jpg


Similar Articles