SQLize Online / PHPize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
-- Variables DECLARE @ControlValue INT = 25; DECLARE @StartDT DATETIME = '2024-07-17 16:25:00'; DECLARE @EndDT DATETIME = '2024-07-17 17:59:00'; DECLARE @StartHour INT = DATEPART(HOUR, @StartDT); DECLARE @EndHour INT = DATEPART(HOUR, @EndDT); -- Create the temporary table CREATE TABLE #TempTable ( HE1 INT, HE2 INT, HE3 INT, HE4 INT, HE5 INT, HE6 INT, HE7 INT, HE8 INT, HE9 INT, HE10 INT, HE11 INT, HE12 INT, HE13 INT, HE14 INT, HE15 INT, HE16 INT, HE17 INT, HE18 INT, HE19 INT, HE20 INT, HE21 INT, HE22 INT, HE23 INT, HE24 INT ); -- Initialize the temporary table with 0s INSERT INTO #TempTable VALUES (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); -- Update the relevant HE columns based on the ControlValue and Start/End hours DECLARE @HEColumn NVARCHAR(10); DECLARE @Hour INT = 1; WHILE @Hour <= 24 BEGIN SET @HEColumn = 'HE' + CAST(@Hour AS NVARCHAR(2)); IF @Hour >= @StartHour AND @Hour <= @EndHour BEGIN EXEC('UPDATE #TempTable SET ' + @HEColumn + ' = ' + CAST(@ControlValue AS NVARCHAR(10))); END SET @Hour = @Hour + 1; END -- Select the result SELECT * FROM #TempTable; -- Drop the temporary table DROP TABLE #TempTable;

Stuck with a problem? Got Error? Ask ChatGPT!

Copy Clear