I am trying to write a stored procedure to return a calculated value from a dataset by writing the result to a table. When I run this code on MySQL 8.0.32, I get an error 1064 Syntax error on the INSERT INTO line. I have tried tweaking this for hours and still can't figure out why it's an error. If I simply Select the AVG(Pct_Saved) without the insert to display in the results pane, it works fine. But I need to save the answer to a table to return to the calling query. It also gets the same error if I try to hardcode the table name instead of using a variable. The select runs from the results of a nested CTE, so I don't know if that could point to a problem. Can anyone see what I'm doing wrong?
SET @userid = LEFT(USER(),POSITION('@' in USER())-1);SET @TempTblName = CONCAT('TEMP',@userid);-- SELECT @TempTblName;# Define the temparary table for the resultsSET @SQLExec = CONCAT('CREATE TABLE IF NOT EXISTS ', 'TEMP',@userid,' (Avg_Savings_Pct DECIMAL(6,2), Avg_ROI_Pct DECIMAL(6,2))');SELECT @SQLExec;PREPARE stmt1 FROM @SQLExec;EXECUTE stmt1;DEALLOCATE PREPARE stmt1;-- WITH CTE AS ( SELECT 576_VMC_Sol_Savings_Pct AS ctePct_Saved, ROW_NUMBER() OVER (ORDER BY 576_VMC_Sol_Savings_Pct) AS row_n FROM v_vmc_summary),iqr AS ( SELECT ctePct_Saved AS Pct_Saved, ( SELECT ctePct_Saved AS quartile_break FROM CTE WHERE row_n = FLOOR((SELECT COUNT(*) FROM v_vmc_summary)*0.75) ) AS q_three, ( SELECT ctePct_Saved AS quartile_break FROM CTE WHERE row_n = FLOOR((SELECT COUNT(*) FROM v_vmc_summary)*0.25) ) AS q_one, 1.5 * (( SELECT ctePct_Saved AS quartile_break FROM CTE WHERE row_n = FLOOR((SELECT COUNT(*) FROM v_vmc_summary)*0.75) ) - ( SELECT ctePct_Saved AS quartile_break FROM CTE WHERE row_n = FLOOR((SELECT COUNT(*) FROM v_vmc_summary)*0.25) )) AS outlier_range FROM CTE ) INSERT INTO @TempTblName (Avg_Savings_Pct) SELECT AVG(Pct_Saved) FROM iqr WHERE Pct_Saved >= q_one - outlier_range AND Pct_Saved <= q_three + outlier_range;
EDIT:Moving the INSERT as suggested still returns the same error:
-- INSERT INTO @TempTblName (Avg_Savings_Pct) SELECT AVG(Pct_Saved) INTO @TempTblName (Avg_Savings_Pct) FROM iqr WHERE Pct_Saved >= q_one - outlier_range AND Pct_Saved <= q_three + outlier_range;