Web www.tizag.com

SQL - Datepart()

Microsoft's SQL Server takes a little different approach to working with dates. It is still possible to extract individual parts of a timestamp and several other functions also work as outlined in SQL - Date.

The difference is that SQL Server uses one main function as oppose to several different functions ie the DATEPART() function. Datepart() requires two parameters, a part argument and a date argument. By part we mean year, day of the year, day of the week, etc. Let's look at an example.

SQL Code:

SELECT DATEPART(week, '2005-12-31');

Return the Week Number:

53

Here we have successfully pulled the "week number" from existing date. SQL's CURRENT_DATE function could be also be substituted or a string value representing the year ('Dec 31, 2005').

The following table lists the datepart() arguments that can be extracted from any given date, time, or timestamp.

partDescriptionAbbreviation(s)
yearreturns a 4 digit yearyy,yyyy
quarterreturns a value 1-4 representing the year's quarterqq,q
monthreturns the numeric equivalent month (1-12)mm,m
dayofyearreturns the day of the year (1-365)dy,y
dayreturns the day of the month (1-31)dd,d
weekreturns the number of the week (1-53)wk,ww
weekdayreturns the number of the day of the week (1-7)dw
hourreturns the number of hours for a given timehh
minutereturns the number of minutes from a given timemi,n
secondreturns the number of seconds in a given timess,s
millisecondreturns the number of milliseconds in a given timems




New - Tizag.com Forums!
Recent Forum Topics: