I have several thousand csv files that I'm attempting to load into a SQL database. I had written a stored procedure to iterate through the file names loaded into a separate table before quickly realizing that the 'LOAD DATA INFILE' command does not work with variable path names.
I then attempted to use a prepared statement to get around this, but the command does not work in a prepared statement either.
Thus, I came to my current workaround of writing the command using variable paths into a separate file, then running the file. However, when running the procedure, I end up with a syntax error around the 'LOAD DATA INFILE' command, but I can't figure out where the issue is coming from.
My code for the procedure is as follows:
DELIMITER //
CREATE PROCEDURE TEST()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE tn TEXT DEFAULT '';
DECLARE p TEXT DEFAULT '';
DECLARE sp TEXT DEFAULT '';
SELECT COUNT(*) FROM `2020_list` INTO n;
SET i = 0;
WHILE i < n DO
SELECT `table_column3` FROM table_name WHERE `table_column1` = i INTO tn;
SET @ct := concat("CREATE TABLE ", tn, "
(.......table column information......);");
PREPARE stmt1 FROM @ct;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
SELECT `table_column2` FROM table_name WHERE `table_column1` = i INTO p;
SET @ft := concat("LOAD DATA LOCAL INFILE '", p, "'
INTO TABLE `", tn, "`
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;");
SELECT `table_column4` FROM 2020_list WHERE `table_column1` = i INTO sp;
SET @cf := concat("SELECT ", @ft, " INTO OUTFILE ", sp, ";");
PREPARE stmt2 FROM @cf;
EXECUTE stmt2;
DEALLOCATE PREPARE stmt2;
SET @rf := concat("SOURCE ", sp, ";");
PREPARE stmt3 FROM @rf;
EXECUTE stmt3;
DEALLOCATE PREPARE stmt3;
SET i = i + 1;
END WHILE;
END;
//
When running the procedure, I end up with the following error:
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LOAD DATA LOCAL INFILE 'Path Name' at line 1
I have pulled various portions of the procedure out and ran them as commands and receive the same result. However, everything that comes out of each variable is what I am expecting and runs as expected in the editor.
Is this a hopeless cause as a workaround to the no variable path names for 'LOAD DATA INFILE', or am I just missing something blaringly obvious in my code? I have another potential workaround, but I was really hoping to automate this process.