Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL change database with variable value

I am setting a variable, and then I want to use the USE command to change the database. Unfortunately USE doesn't 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'

So the value of the variable is not evaluated when I try to connect. Any ideas?

like image 838
bioShark Avatar asked Mar 29 '12 08:03

bioShark


People also ask

How do I change the value of a variable in MySQL?

To assign a value to a session system variable, precede the variable name by the SESSION or LOCAL keyword, by the @@SESSION. , @@LOCAL. , or @@ qualifier, or by no keyword or no modifier at all: SET SESSION sql_mode = 'TRADITIONAL'; SET LOCAL sql_mode = 'TRADITIONAL'; SET @@SESSION.

Can we store value in variable in MySQL?

You can store a value in a user-defined variable in one statement and refer to it later in another statement. This enables you to pass values from one statement to another. User variables are written as @ var_name , where the variable name var_name consists of alphanumeric characters, . , _ , and $ .

What does := do in MySQL?

This means you can use := in any valid SQL statement (not just in SET statements) to assign a value to a variable. While it is also possible both to set and to read the value of the same variable in a single SQL statement using the := operator, this is not recommended.


1 Answers

I have found my own solution, so I am going to answer my own question, in case anybody is interested.

@outis you are right, it's not possible to use a variable with the command USE.

However, due to the fact that I want to create a table in a 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;

So basically this solution builds up the statement, prepares it and executes it. @schema parameter can even be past down to the script. This way I dynamically build the create statement.

like image 186
bioShark Avatar answered Sep 30 '22 06:09

bioShark