I have a Cursor loop that performs a select statement 230 times for each Station ID I have. The select statement gets temperatures for Jan 1st over the past ten years for the current Station ID, Dumps it into a temporary table, then I take the average for Jan 1st over the 10 years and save it to a table.
What I want to do is add another loop to go through each day of the year for each station. Essentially I am trying to calculate the 10 year average temperature for each day of the year from 230 different stations.
Here is the code I have so far. I was wondering if there was a better way to do this or how to add a nested while loop?
DECLARE @StationID AS int
DECLARE @GetStationID AS CURSOR
DECLARE @Dte AS DATETIME
SET @Dte = '1/1/2025 00:00:00'
SET @GetStationID = CURSOR FOR
SELECT dbo.Trim(WBAN) FROM Station_Ref_ID
OPEN @GetStationID
FETCH NEXT
FROM @GetStationID INTO @StationID
WHILE @@FETCH_STATUS = 0
BEGIN
WHILE @Dte < '1/1/2026'
BEGIN
SELECT [Station ID], Dates, [Low Temp], [Avg Temp], [High Temp]
INTO TenYr
FROM Archive
WHERE (CAST(MONTH(Archive.Dates) AS VARCHAR(2)) +'/'+ CAST(DAY(Archive.Dates) AS VARCHAR(2))) = CAST(MONTH(@Dte) AS VARCHAR(2)) + '/' + CAST(DAY(@Dte) AS VARCHAR(2))
AND YEAR(Dates) BETWEEN 1999 AND 2008 AND [Station ID] Like @StationID
INSERT INTO TenYrData
([Station ID], Dates, [Low Temp], [Avg Temp], [High Temp])
SELECT @StationID, @Dte, ROUND(AVG([Low Temp]),2), ROUND(AVG([Avg Temp]),2), ROUND(AVG([High Temp]),2)
FROM TenYr
DROP TABLE TenYr
SET @Dte = DATEADD(DAY, 1, @Dte)
END
FETCH NEXT
FROM @GetStationID INTO @StationID
END
CLOSE @GetStationID
DEALLOCATE @GetStationID
What I want to do is add another loop to go through each day of the year for each station. Essentially I am trying to calculate the 10 year average temperature for each day of the year from 230 different stations.
Here is the code I have so far. I was wondering if there was a better way to do this or how to add a nested while loop?
DECLARE @StationID AS int
DECLARE @GetStationID AS CURSOR
DECLARE @Dte AS DATETIME
SET @Dte = '1/1/2025 00:00:00'
SET @GetStationID = CURSOR FOR
SELECT dbo.Trim(WBAN) FROM Station_Ref_ID
OPEN @GetStationID
FETCH NEXT
FROM @GetStationID INTO @StationID
WHILE @@FETCH_STATUS = 0
BEGIN
WHILE @Dte < '1/1/2026'
BEGIN
SELECT [Station ID], Dates, [Low Temp], [Avg Temp], [High Temp]
INTO TenYr
FROM Archive
WHERE (CAST(MONTH(Archive.Dates) AS VARCHAR(2)) +'/'+ CAST(DAY(Archive.Dates) AS VARCHAR(2))) = CAST(MONTH(@Dte) AS VARCHAR(2)) + '/' + CAST(DAY(@Dte) AS VARCHAR(2))
AND YEAR(Dates) BETWEEN 1999 AND 2008 AND [Station ID] Like @StationID
INSERT INTO TenYrData
([Station ID], Dates, [Low Temp], [Avg Temp], [High Temp])
SELECT @StationID, @Dte, ROUND(AVG([Low Temp]),2), ROUND(AVG([Avg Temp]),2), ROUND(AVG([High Temp]),2)
FROM TenYr
DROP TABLE TenYr
SET @Dte = DATEADD(DAY, 1, @Dte)
END
FETCH NEXT
FROM @GetStationID INTO @StationID
END
CLOSE @GetStationID
DEALLOCATE @GetStationID