Question

Is it possible to LOAD DATA INFILE within a table name set in a user variable ?

Here is the script that doesn't work:

INSERT INTO Demand (name, comment, scale) VALUES (A,A,1); 
SET @Demand_id = LAST_INSERT_ID(); 

 INSERT INTO Matrices (name, comment, total) VALUES (Matrix_0_1); 
 SET @Matrices_last_id = LAST_INSERT_ID(); 
     INSERT INTO DemandSegment (usertype, Matrix, scale) SELECT 1, id, 2 FROM Matrices WHERE id = @matrice_last_id; 
     SET @DemandSegment_last_id = LAST_INSERT_ID(); 
     INSERT INTO Demand_DemandSegment (Demand_id, DemandSegment_id) VALUES(@Demand_id, @DemandSegment_last_id); 

     SET @matrix_creation = CONCAT("CREATE TABLE Matrix_",@matrices_last_id," LIKE Matrix_2");
     PREPARE stmt from @matrix_creation;
     EXECUTE stmt;
     DEALLOCATE PREPARE stmt;

     SET @matrix_insertion = CONCAT("LOAD DATA INFILE '0.csv' INTO TABLE Matrix_",@Matrices_last_id);
     PREPARE stmt from @matrix_insertion;
     EXECUTE stmt;
     DEALLOCATE PREPARE stmt;

Here is the error I get:

ERROR 1295 (HY000): This command is not supported in the prepared statement protocol yet

ERROR 1243 (HY000): Unknown prepared statement handler (stmt) given to EXECUTE

ERROR 1243 (HY000): Unknown prepared statement handler (stmt) given to DEALLOCATE PREPARE

If, as I can read, it's impossible to do so, do you see any alternatives ?

Was it helpful?

Solution

One alternative is to LOAD DATA into a temporary table, then copy the temporary table to the real table.

CREATE TEMPORARY TABLE Matrix_temp LIKE Matrix_2;
LOAD DATA INFILE '0.csv' INTO TABLE Matrix_temp; -- not a prepared statement

SET @matrix_creation = CONCAT('CREATE TABLE Matrix_',@matrices_last_id,
 ' LIKE Matrix_2');
PREPARE stmt from @matrix_creation;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @matrix_insertion = CONCAT('INSERT INTO Matrix_',@Matrices_last_id, 
 ' SELECT * FROM Matrix_temp');
PREPARE stmt from @matrix_insertion;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Beware of the risk of using temporary tables in this way if you also use replication. If the slave restarts, temporary tables are lost. If this happens between populating the temporary table and copying it to a permanent table, then you can break replication.

It sounds like such a thing would never happen, and yet this is pretty common.
See http://dev.mysql.com/doc/refman/5.6/en/replication-features-temptables.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top