Wednesday, February 13, 2008

Calculating date differences in T-SQL

In the past, I always used custom functions to calculate the differences between dates in MS-SQL (T-SQL) when I wanted the date part to be months or years. I came across a very simple way of doing it without a stored function call.

select dateadd(dd, -15,getdate())

Simple, huh?

The date part can be dd (day), mm (month) or yy (year). The next argument is the number of date parts to add or subtract. The third argument is the original date we are calculating the difference from. In the above example, we are using the getdate() function to use the current date and time.

No comments: