Wednesday, 26 June 2013

How To Use DATEPART() Function In SQL

sql - datepart


In previous chapter i have explained How To Use DATEADD() Function In SQL

now i am gonna eplain you How To Use DATEPART() Function In SQL


DATEPART() is a SQL function used to extract all kinds of date information from timestamps, and it is a function that is unique to Microsoft's SQL Server Application.

SQL Datepart:

USE mydatabase;

SELECT DATEPART(year, '2007-06-01') AS "Year";

SQL Results:

Year
2007
DATEPART() requires 2 parameters separated by a comma (,). The first parameter specifies what type of date data will be extracted, and the second parameter is a timestamp value.

SQL Datepart:

USE mydatabase;

SELECT DATEPART(year, '2007-06-01') AS "Year",
    DATEPART(month, '2007-06-01') AS "Month",
    DATEPART(day, '2007-06-01') AS "Day",
    DATEPART(dayofyear, '2007-06-01') AS "DayofYear",
    DATEPART(weekday, '2007-06-01') AS "Weekday";

SQL Results:

YearMonthDayDayofYearWeekday
2007611526

Datepart Abbreviation Chart:

DatePartAbbreviationExample
yearyy, yyyyDATEPART(yy, getdate())
quarterqq, qDATEPART(qq, getdate())
monthmm, mDATEPART(mm, getdate())
dayofyeardy, yDATEPART(dy, getdate())
daydd, dDATEPART(dd, getdate())
weekwk, wwDATEPART(wk, getdate())
weekdaydwDATEPART(dw, getdate())
hourhhDATEPART(hh, getdate())
minutemiDATEPART(mi, getdate())
secondssDATEPART(ss, getdate())
millisecondmsDATEPART(ms, getdate())

No comments: