Thursday, May 21, 2009

Know how to retrieve components of a date using SQL...!!!

You can retrieve different components of date from timestamp using SQL functionDATEPART. You can extract date components like YEAR, MONTH, DAY, HOUR, MINUTE, SECOND using this Datepart function. The syntax for using this function is

datepart(date component to retrieve, date)

Example: Suppose you want to retrieve year component from customer table's DOB column having timestamp type, the query will be like

Select datepart(year, DOB) from customer where cust_name='xyz'

ResultSet:- 1984

Same way you can use:
datepart(day, DOB) for day
datepart(minute, DOB) for minute
datepart(month, DOB) for month
datepart(hour, DOB) for HOUR
datepart(second, DOB) for second

The above function works fine with SQLServer but with Oracle and MySql I guess it wont work. In that case you can use extract(year from DOB).

No comments:

Post a Comment