SQL Server Code Example

Output a Date Range

A practical SQL Server date and time example for Output a Date Range.

Example and Notes

Use this SQL Server example as a starting point for development, troubleshooting, reporting, or maintenance work. Review it against your schema, data volume, permissions, and SQL Server version before using it in production.

This sql function is very useful for returning every date between a start and end date you pass to the function. The code below will show you how to accomplish that.

Create FUNCTION [dbo].[DateRange]
(     
      @Increment              CHAR(1),
      @StartDate              DATETIME,
      @EndDate                DATETIME
)
RETURNS  
@SelectedRange    TABLE 
(IndividualDate DATETIME)
AS 
BEGIN
      ;WITH cteRange (DateRange) AS (
            SELECT @StartDate
            UNION ALL
            SELECT 
                  CASE
                        WHEN @Increment = 'd' THEN DATEADD(dd, 1, DateRange)
                        WHEN @Increment = 'w' THEN DATEADD(ww, 1, DateRange)
                        WHEN @Increment = 'm' THEN DATEADD(mm, 1, DateRange)
                  END
            FROM cteRange
            WHERE DateRange <= 
                  CASE
                        WHEN @Increment = 'd' THEN DATEADD(dd, -1, @EndDate)
                        WHEN @Increment = 'w' THEN DATEADD(ww, -1, @EndDate)
                        WHEN @Increment = 'm' THEN DATEADD(mm, -1, @EndDate)
                  END)
          
      INSERT INTO @SelectedRange (IndividualDate)
      SELECT DateRange
      FROM cteRange
      OPTION (MAXRECURSION 3660);
      RETURN
END

GO

A sample call to this function would be:
Select * From dbo.DateRange('d','10/1/18','10/29/18')
which would return:

Production Review

WSI can adapt this script for your database, improve error handling, tune performance, document the logic, and help deploy it safely.

Readable Example

The original sample is preserved and presented in a cleaner professional layout.

Practical Context

Each example is framed around how it may be used in real SQL Server work.

Expert Support

WSI can adapt examples for your specific schema, business rules, and performance needs.

About Us

WSI is a small business and a leading provider of custom SQL Server/Azure programming and database solutions for government entities, Fortune 1000 companies, and emerging businesses. We are your custom SQL Server/Azure development experts.

Privacy Notice

We use essential cookies to make this site work. With your permission, we may also use analytics or marketing cookies.