By: Michael otey
From the September 2009 edition of SQL Server magazine
Dealing with date values is a core part of working with T-SQL, and SQL server has several built-in functions to access and manipulate dates in your T-SQL scripts, functions, and stored procedures. below are some essential T-SQL functions that work with SQL Server's classic datetime data type. SQL Server 2008's newer functions also deal with the new date, time, and datetime2 data types.
1. getdate ()
Probably the most essential of the date4 functions,
Select getdate ()
Returns a datetime data type containing the current system data and time: 11:52:26. 687.
2. dateadd (datepart, number, date)
Dateadd lets you add values to a given date and returns the result as a datetime data type. Entering
Select dateadd (day, 30, getdate ())
Adds 30 days to the date from the example abve: 12:01:38. 950.
3. datediff (datepart, startdate, enddate)
This function returns a single integer data type that represents the difference between two dates. It can return values for years, months, days, hours, minutes, seconds, milliseconds, and more:
Select datediff (day, '2014/1/123', getdate ())
Returns 187 as the difference in days between the example date and the beginning of the year.
4. datepart (datepart, date)
To return an integer that represents a portion of a valid date, datepart extracts all parts of the datetime data type including years, months, days, hours, minutes, seconds and milliseconds:
Select datepart (month, getdate ())
Returns 7 as the example date's month.
5. datename (datepart, date)
Like its name suggests, datename returns the name of a given part of the date:
Select datename (month, getdate ())
It can return almost all parts of the date including the name of the quarter, the weekday, or as here, the Month: July.
6. isdate (expression)
This function tests if the value supplied is a valid date:
Select isdate ('2014/1/09 ')
In this case, it returns a value of 0 (false) indicating the date is invalid; if it returns a value of 1 (true), the date is valid.
7. Day (date), month (date), Year (date)
These date functions are like datepart but a bit easier to work:
Select month (0), Day (0), Year (0)
They each return an integer representing the supplied date value-in this case, 1900.