27

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;
4
  • Any particular programming language or environment? The connection with the database is where this is specified. Commented Mar 31, 2009 at 13:35
  • it's just mysql.. I'll dump it to myadmin Commented Mar 31, 2009 at 13:37
  • 2
    Could you use a use statement dev.mysql.com/doc/refman/5.0/en/use.html? Commented Mar 31, 2009 at 13:38
  • I have select data from one db and insert it into another db.. Commented Mar 31, 2009 at 13:39

3 Answers 3

33

With considerable effort, yes.

SET @db = 'db1';
SET @q = CONCAT('SELECT * FROM ', @db, '.mycol');
PREPARE stmt FROM @q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Sign up to request clarification or add additional context in comments.

Comments

1

Using Chaos' 'Prepare Statement' solution I managed to create a Stored Procedure which uses a variable database name.

Works like a charm for migrating data from one database to another with a Stored Procedure. This way the code isn't pinned to a single database.

DELIMITER $$

DROP PROCEDURE IF EXISTS `SampleProcedure` $$
CREATE PROCEDURE `SampleProcedure`(IN HubDatabaseName VARCHAR(255))
BEGIN

SET @db = HubDatabaseName;
SET @q = CONCAT('

/* Import data from Hub database to local database */
INSERT INTO `table_name_in_local_database`
SELECT
  *
FROM
  ', @db ,'.`tablename`

');

PREPARE stmt FROM @q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

END $$
DELIMITER ;

Comments

0

If you have PHP installed you could use this script to replace the mysql variables to there actual value:

<?php

$sqlFile = 'migration.sql';
$fromDb = 'db1';
$toDb = 'db2';

echo str_replace(['@fromDb', '@toDb'], [$fromDb, $toDb], file_get_contents($sqlFile));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.