mysql create table dynamically

前端 未结 1 619
北恋
北恋 2020-12-02 00:39

I am creating a database on mysql. First creating the principal tables which on average has 30 columns per table. And the standard of the log table is the pk of the referenc

相关标签:
1条回答
  • 2020-12-02 01:38

    To make a string represent a table (or database) name you will need to concat your query string with the variable and prepare/execute a statement right in the stored procedure. Here's a basic example.

    -- DROP PROCEDURE IF EXISTS createLogTable;
    DELIMITER //
    CREATE PROCEDURE createLogTable(tblName VARCHAR(255))
    BEGIN
        SET @tableName = tblName;
        SET @q = CONCAT('
            CREATE TABLE IF NOT EXISTS `' , @tableName, '` (
                `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
                `something` VARCHAR(10) NOT NULL,
                `somedate` DATETIME NOT NULL,
                PRIMARY KEY (`id`)
            ) ENGINE=MyISAM DEFAULT CHARSET=utf8
        ');
        PREPARE stmt FROM @q;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
        -- and you're done. Table is created.
        -- process it here if you like (INSERT etc)
    END //
    

    Then… CALL createLogTable('exampleTable');

    So the basic idea is

    1. concat the procedure parameter(s) with your query as necessary
    2. prepare/execute a statement from this query string
    0 讨论(0)
提交回复
热议问题