MySQL在其他查询中使用prepare语句结果

时间:2018-03-27 10:11:49

标签: mysql sql

我想使用prepare语句结果来填充我的临时表。可能吗? (如果我尝试在存储过程中执行此操作。)

我想这样的事情:

SET @table_name = 'my_table';
SET @query = CONCAT('SELECT * FROM ', @table_name);
PREPARE statement FROM @query;
INSERT INTO tmp_table FROM statement;
DEALLOCATE PREPARE statement;

1 个答案:

答案 0 :(得分:2)

首先创建临时表

SET @table_name = 'my_table';
SET @query = CONCAT('CREATE TEMPORARY TABLE tmp_table AS SELECT * FROM ', @table_name);
PREPARE statement FROM @query;
EXECUTE statement ;
DEALLOCATE PREPARE statement;