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:
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 ;