Introduction: In this short article I am going to share how to create a table valued user defined function to get all dates between specified date range in Sql server.
In previous articles i explained How to Get first, last date and total days in year or month
and Declare and use table variables in sql server and Using CTE to get all dates between two specified dates and 20 main differences between stored procedures and functions and Get created or modified date of tables, stored procedures, views and functions
Description: While working with sql server database we often need to deal with dates. Few days back I need to get the dates between the date range I specify.
There are many ways to get this but here I have created a function to get the desired result.
We can call this function whenever we need just by passing the start and end date. It will return all the dates between these two dates.
Implementation: Let’s create a user defined function to get the dates between date range.
CREATE FUNCTION GetAllDatesBetweenRange
SELECT TOP (DATEDIFF(DAY, @StartDate, @EndDate) + 1)
DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY A.object_id) - 1, @StartDate) As DateList
FROM sys.all_objects A CROSS JOIN sys.all_objects B
To call above created function we need to write as:
SELECT * FROM GetAllDatesBetweenRange('2017-01-01','2017-01-10')
Result will be as shown in image above.
Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates.