Sql Server - Function to Generate Date Range with differences like day,month,year
CREATE FUNCTION [dbo].[DateRange] ( @Increment CHAR(1), @StartDate DATETIME, @EndDate DATETIME, @Custom INT ) 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) WHEN @Increment = 'y' THEN DATEADD(yy, 1, DateRange) WHEN @Increment = 'c' THEN DATEADD(DAY, @Custom, 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) WHEN @Increment = 'y' THEN DATEADD(yy, -1, @EndDate) WHEN @Increment = 'c' THEN DATEADD(DAY, -@Custom, @EndDate) END) INSERT INTO @SelectedRange (IndividualDate) SELECT DateRange FROM cteRange OPTION (MAXRECURSION 3660); RETURN END
No comments:
Post a Comment