Click here to monitor SSC
SQLServerCentral is supported by Redgate
 
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: 456 | Views in the last 30 days: 4
 
Related Articles
SCRIPT

Days of month function

Functions return tables with days of the specified month.

SCRIPT

Function to get number of days in month

Function to get number of days in month

SCRIPT

Month Name

Function to return the Month Name for month number input

SCRIPT

Function for Getting Interval Dates by days,months,years.

Function for Getting Interval Dates by days,months,years for particular week number, for particular ...

FORUM

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

 
Contribute