variable database name

后端 未结 3 1104
余生分开走
余生分开走 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:00

    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));
    
    0 讨论(0)
  • 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 ;
    
    0 讨论(0)
  • 2020-12-09 04:22

    With considerable effort, yes.

    SET @db = 'db1';
    SET @q = CONCAT('SELECT * FROM ', @db, '.mycol');
    PREPARE stmt FROM @q;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    
    0 讨论(0)
提交回复
热议问题