variable database name

后端 未结 3 1103
余生分开走
余生分开走 2020-12-09 03:38

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:

         


        
3条回答
  •  囚心锁ツ
    2020-12-09 04:08

    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 ;
    

提交回复
热议问题