≡ Menu

Using TransactSQL ‘Datepart’ to return single part of date/time

  •  
  •  
  •  

A very useful function in SQL is ‘datepart’ which can be used to retrieve a particular part (such as day, month etc) from a date/time field.

For example, let us say you need to retrieve the count of all records from a table by date.

Select datepart(day,timestamp),count(*) from my_Log with (nolock)

Where status = ‘ERROR’

Group by datepart(day,log_date)

In the above query:

My_log: Table name

Log_date: column that is of date/time type

Here is all the ‘datepart’ you can use:

year

quarter

month

dayofyear

day

week

weekday

hour

minute

second

millisecond

microsecond

nanosecond

TZoffset

ISO_WEEK


  •  
  •  
  •  

Comments on this entry are closed.