MySQL Variables storing database name

心已入冬 提交于 2019-12-01 09:16:50

问题


I have a long script that I need to run on several different databases (all witht he same tables and field names).

What I would like to do is something like this:

1  SET @TARGET_DATABASE = 'beta'
2  SET @SOURCE_DATABASE = 'sandbox';
3  
4  CREATE DATABASE IF NOT EXISTS @TARGET_DATABASE;
5  USE @TARGET_DATABASE;

...

10 INSERT INTO `tableFoo` SELECT * FROM @SOURCE_DATABASE.`tableFoo`;

On line 10 I get an error (I'm not surprised): "Script line: 10 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 '@SOURCE_DATABASE.tableFoo' at line..."

So I tried this insted for line 10:

10 SET @TABLE=CONCAT('`',@SOURCE_DATABASE,'`','.`tableFoo`');
11 INSERT INTO `tableFoo` SELECT * FROM @TABLE;

...and again error "Script line: 11 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 '@TABLE' at line..." As you can see, line 10 works fine...

Is there any way to refer to a table in a database with a variable?

// Thank you.


回答1:


It will work if you concat the entire query. Try:

set @db = 'mydb';
set @tble = 'table';

set @query = concat('INSERT INTO tablefoo SELECT * FROM ', @db, '.', @tble);
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


来源:https://stackoverflow.com/questions/5530755/mysql-variables-storing-database-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!