SET DATEFIRST 1; DECLARE @sDate date DECLARE @eDate date;...

0

Please login or register to vote for this query.

(click on this box to dismiss)

Mythology

Q&A for enthusiasts and scholars of mythology and folklore

SET DATEFIRST 1;
DECLARE @sDate date
DECLARE @eDate date;
DECLARE @noModificationYears nvarchar(max);
SET @sDate = '2020-01-01';
SET @eDate = '2020-12-31';
SET @noModificationYears = '2018,';

;with CTE1 As  
(  
    Select DATEADD(day, 0, @sDate) as TheDate, 'D' as PERIND
    UNION ALL  
    Select DATEADD(day, 1, TheDate) as TheDate, 'D' as PERIND from CTE1  
    where TheDate < @eDate
)
,CTE2 As
        (
        Select c1.TheDate, 'D' as PERIND from CTE1 c1
        UNION ALL
        Select DATEADD(day, 0, c2.TheDate) as TheDate, 'W' as PERIND from CTE1 c2
        )
/*,CTE2 AS (
      SELECT DATEPART(week, TheDate) AS WeekOfYear, DATEPART(year, TheDate) AS TheYear
      FROM CTE1 GROUP BY DATEPART(week, TheDate), DATEPART(year, TheDate) 
      HAVING Count(DATEPART(year, TheDate)) = 7 AND DATEPART(week, TheDate) = '1'     
)*/
--SELECT * from CTE2

SELECT
    c1.TheDate AS Date,
    DATEPART(year, c1.TheDate) AS DateYear,
    DATEPART(month, c1.TheDate) AS DateMonth,
    DATEPART(week, c1.TheDate) as DateWeek,
    datepart(year, dateadd(dd, -datepart(dw, c1.TheDate) + 1, c1.TheDate)) as CalculatedWeekYear,
    CASE 
      WHEN
        CHARINDEX(cast(DATEPART(year, TheDate) as varchar(8000)), @noModificationYears) > 0
      THEN
        DATEPART(week, c1.TheDate)
      ELSE
        CASE
          WHEN
            DATEPART(week, c1.TheDate) != 1
          THEN
            DATEPART(week, c1.TheDate) - 1
          ELSE
            CASE
              WHEN
              CHARINDEX(cast((DATEPART(year, TheDate) - 1) as varchar(8000)), @noModificationYears) = 0
              THEN
                DATEPART(week, CONCAT(datepart(year, TheDate) - 1, '-12-31')) - 1
              ELSE
                DATEPART(week, CONCAT(datepart(year, TheDate) - 1, '-12-31'))
            END
        END
      END AS CalculatedWeek
FROM CTE2 AS c1
option (maxrecursion 0);

Enter Parameters

Options:
Switch sites:
loading Hold tight while we fetch your results