Hullo,
Can any help me shed some light on what's going on when I try to prepare a statement from a string that contains a cursor-fetched variable?
Below is the procedure that I'm trying to create.
When I create it without the prepared statement, and replace those three lines with SELECT @export_sql_stmt
, the output verifies that the SQL statement is being constructed correctly; but with the prepared statement, the value of @export_sql_stmt
is NULL. That confuses me...
Any help would be most gratefully received!
DELIMITER //
CREATE PROCEDURE generate_district_files()
BEGIN
-- Declare variables
DECLARE district_val VARCHAR(50); -- The name of the current district
DECLARE no_more_rows BOOLEAN; -- Loop exit condition; set by NOT FOUND handler
-- Declare the cursor
DECLARE districts_cur CURSOR FOR SELECT district FROM staking_jobs GROUP BY district;
-- Declare handler to set loop exit condition
DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rows = TRUE;
-- Get the districts
OPEN districts_cur;
-- Loop through each district, creating a CSV file for each
the_loop: LOOP
-- Get the district name
FETCH districts_cur INTO district_val;
-- exit the loop if there were no records, or we've processed them all
IF no_more_rows THEN
CLOSE districts_cur;
LEAVE the_loop;
END IF;
-- Output the CSV file for this district
--
-- Set up the statement for exporting (required because of dynamic filename)
SET @export_sql_stmt = CONCAT('SELECT district, \'s\', pick_id',
' FROM staking_jobs WHERE district = \'', district_val, '\'',
' INTO OUTFILE \'/tmp/to_be_staked_', district_val, '.csv\'',
' FIELDS TERMINATED BY \',\' OPTIONALLY ENCLOSED BY \'"\'');
PREPARE stmt1 FROM @export_sql_stmt;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END LOOP the_loop;
END //
DELIMITER ;
Thank you!