Ask Ben: Selecting Parts of a Date/Time Stamp In SQL

Posted July 26, 2006 at 6:27 PM

Tags: SQL, Ask Ben

How can I select the month part of date value in SQL server?

I get this type of question a lot: How can I select the hours from the date in SQL? How can I get the day of the year from a date? How can I get the day of the month from a date? For all of these, the easiest solution would be to use SQL Server's built in date/time function: DatePart(). It allows you to select individual parts of a date:

 Launch code in new window » Download code as text file »

  • SELECT
  • id,
  • (
  • DATEPART(
  • mm, -- mm: Select only the month
  • birthday
  • )
  • ) AS birthday_month
  • FROM
  • girlfriends

It's a fairly straight forward function. You can of course do more than getting the months (as in the example). You can get all different parts of the date by specifying a different first argument:

year: yy, yyyy
quarter: qq, q
month: mm, m
dayofyear: dy, y
day: dd, d
week: wk, ww
weekday: dw
hour: hh
minute: mi, n
second: ss, s
millisecond: ms

You can learn more about this function at the MSDN website.

Download Code Snippet ZIP File

Comments (0)  |  Post Comment  |  Ask Ben  |  Permalink  |  Other Searches  |  Print Page



Adobe ColdFusion 8.0.1 Update - Helping Programmers To Be Signifanctly Less Girlie - Download ColdFusion 8 Update 8.0.1 Now.

Reader Comments

There are no comments posted for this web log entry.


Post Comment  |  Ask Ben


Home   |   Web Log   |   ColdFusion   |   Projects   |   Resume   |   Job Form   |   Search   |   Contact
Epicenter Consulting - Custom Software Solutions for Business Evolution HostMySite.com - The Leader In ColdFusion Hosting