动态表名称&加载数据信息

时间:2013-05-15 19:12:45

标签: mysql load-data-infile dynamic-tables

是否可以在用户变量中设置的表名中加载数据INFILE?

以下是不起作用的脚本:

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;

这是我得到的错误:

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

如果我可以阅读,那么这是不可能的,你有没有其他选择?

1 个答案:

答案 0 :(得分:-1)

另一种方法是将DATA加载到临时表中,然后将临时表复制到真实表中。

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;

如果您还使用复制,请注意以这种方式使用临时表的风险。如果从站重新启动,则临时表将丢失。如果在填充临时表和将其复制到永久表之间发生这种情况,则可以中断复制。

这听起来似乎永远不会发生,但这很常见 见http://dev.mysql.com/doc/refman/5.6/en/replication-features-temptables.html