Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
Log in  ::  Register  ::  Not logged in

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

UDF for date ranges around a given date (updated)

By pshotts,

UDF - SQL 2000 and higher

This function returns an 18 row table of date ranges around a given date.
The ranges are: Day, Week (Sunday to Saturday), Month, Quarter, Half Year, Year.
For each range there are 3 values: Previous, Same and Next

Example of usage:
Joined to an orders table:

Select r.period, count(o.order_id)
from orders o
inner join dbo.ufn_date_ranges('2003-04-01') r
on o.order_date between r.start_date and r.end_date
where r.period_length = 'quarter'
group by r.period

The function requires a view v_now, which is also created by this script.
When the function is passed null as its parameter instead of a specific datetime value it gives results for the current timestamp: ie today, yesterday, tomorrow or this month and last month etc...

Total article views: 455 | Views in the last 30 days: 4
Related Articles

Days of month function

Functions return tables with days of the specified month.


Function to get number of days in month

Function to get number of days in month


Month Name

Function to return the Month Name for month number input


I need to create a function that returns a date 6 months from getutc date

I need to create a function that returns a date 6 months from getutc date





Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones