Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable database name

Tags:

Is there any way in MySQL to put the name of the database into a variable? For example, when I have a database called 'db1', can I do something like this:

set @db= 'db1'; select * from @db.mytable; 

EDIT: There is another example of what I want to do:

set @dbfrom= 'db1'; set @dbto= 'db2'; insert into @dbto.mytable (col1,col2,col3) select col2,col1,col3 from @dbfrom.mytable; 
like image 388
grilix Avatar asked Mar 31 '09 13:03

grilix


People also ask

What is a variable database?

When you are collecting data in a database, you need a unique identifier for each of the individual items you are collecting. This identifier is usually called a variable or database element. The identifier is called a variable because the data it contains (the data element) can vary depending on the individual record.

Can you name variables in SQL?

Like other programming languages, a variable in PL/SQL must follow the naming rules as follows: The variable name must be less than 31 characters. Try to make it as meaningful as possible within 31 characters. The variable name must begin with an ASCII letter.

What is data variable in SQL?

A Transact-SQL local variable is an object that can hold a single data value of a specific type. Variables in batches and scripts are typically used: As a counter either to count the number of times a loop is performed or to control how many times the loop is performed.


1 Answers

With considerable effort, yes.

SET @db = 'db1'; SET @q = CONCAT('SELECT * FROM ', @db, '.mycol'); PREPARE stmt FROM @q; EXECUTE stmt; DEALLOCATE PREPARE stmt; 
like image 121
chaos Avatar answered Sep 20 '22 09:09

chaos