MySQL variable value database

I set a variable and then I want to use the command USEto modify the database. Unfortunately, it USEdoes not evaluate the variable.

SET @con="testDB";
Query OK, 0 rows affected (0.00 sec)
select @con;
+--------+
| @con   |
+--------+
| testDB |
+--------+
1 row in set (0.00 sec)
use @con;
ERROR 1049 (42000): Unknown database '@con'

Thus, the value of the variable is not evaluated when trying to connect. Any ideas?

+5
source share
2 answers

I found my own solution, so I'm going to answer my question if anyone is interested.

@outis you're right, it is impossible to use a variable with a command USE.

However, due to the fact that I want to create a table in the database specified at runtime, my solution would be to use dynamic SQL:

set @schema="testDB";
set @front="CREATE TABLE IF NOT EXISTS ";
set @endpart=".`TEST1` (DIM_ID INT(16)) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_unicode_ci;";
set @stat=concat(@front,@schema,@endpart);
prepare command from @stat;
execute command;

, , . @schema script. , create.

+5

, USE @var;. .

USE testDB;
SET @schema = DATABASE();
0

All Articles