I cannot figure out where I've messed this up. Full code:
DECLARE @start_date DATETIME, @end_date DATETIME
DECLARE @Table TABLE (StartDate DATETIME, Enddate DATETIME, WeekNo INT)
SET @start_date = '2017-01-01'
SET @end_date = '2017-12-31'
INSERT INTO @Table
SELECT
MIN(dt), MAX(dt), w
FROM
(SELECT
dt, year(dt) y, DATEPART(week, dt) w
FROM
(SELECT
@start_date + (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1) dt
FROM
sys.columns s1
CROSS JOIN
sys.columns s2) q
WHERE
dt BETWEEN @start_date AND @end_date) a
GROUP BY
y, w
I've narrowed down where the error is happening. It happens here:
SELECT
dt, year(dt) y, DATEPART(week, dt) w
FROM
(SELECT
@start_date + (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1) dt
FROM
sys.columns s1
CROSS JOIN
sys.columns s2) q
WHERE
dt BETWEEN @start_date AND @end_date
If I run just this part I get the error:
Arithmetic overflow error converting expression to data type datetime.
I've tried adding in some CONVERT here and there trying to find where it's messing up, but I can not figure it out.
I have seen a couple of others who had a similar problem, but neither this one or this one have any solution that is helpful to me.
I'm new to the set based SQL programming, I'm self-taught in loops so this is out of my depth. Any help is appreciated.
@start_date + (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1)to add a day?@Start_Dateand continuing till I stop the query.datetimebut i'd suggest sticking todateadd()for explicit reasons and code management. Many people misuse this.dateadd(day, (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1),@start_date)since you need the RN from the table it seemsselectstatement for each of the parts of@start_date + DATEADD(day, 1, @start_date. Obviously, the first part will just display whatever@start_date is, but what does the second portion do? You are trying to add a day to it and then add it back to itself currently. Also, you know where the issue is, and you also know where it is not (inside theselectstatement). Get rid of thewhereclause, does that get rid of it? No? Replace theselectwith justselect *. How about now? Code is small so get rid of or isolate to find it.