November 21, 2010

Get all the dates between two dates in SQL Server

CREATE FUNCTION [dbo].[GetDatesInBetween](@FromDate DATETIME, @ToDate DATETIME, @IncludeWeekends BIT )

RETURNS @DateTable TABLE(DATE DATETIME)
AS
BEGIN
INSERT INTO @DateTable (DATE) VALUES (@FromDate)
WHILE @FromDate < @ToDate
BEGIN
SELECT @FromDate = DATEADD(D, 1, @FromDate)
IF @IncludeWeekends = 1
INSERT INTO @DateTable (DATE) VALUES (@FromDate)
ELSE IF DATENAME(dw, @FromDate) <> 'Thursday' AND DATENAME(dw, @FromDate) <> 'Friday'
INSERT INTO @DateTable (DATE) VALUES (@FromDate)
END
RETURN
END

No comments:

Post a Comment