MySQL查询动态创建表?
为此,您可以使用存储过程。让我们动态创建一个具有两列的表,即StudentId为int,而StudentName为varchar-
DELIMITER $$ CREATE PROCEDURE creatingDynamicTableDemo(yourTableName VARCHAR(200)) -> BEGIN -> SET @name = yourTableName; -> SET @st = CONCAT(' '> CREATE TABLE IF NOT EXISTS `' , @name, '` ( '> `StudentId` int UNSIGNED NOT NULL AUTO_INCREMENT, '> `StudentName` varchar(20) NOT NULL, '> PRIMARY KEY (`StudentId`) '> ) '> '); -> PREPARE myStatement FROM @st; -> EXECUTE myStatement; -> DEALLOCATE PREPARE myStatement; -> END $$ DELIMITER ;
上面,我们将StudentId设置为PRIMARYKEY。
借助CALL命令调用存储过程-
call creatingDynamicTableDemo('DemoTable');
现在您可以检查表的说明-
desc DemoTable;
输出结果
这将产生以下输出-
+-------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+------------------+------+-----+---------+----------------+ | StudentId | int(10) unsigned | NO | PRI | NULL | auto_increment | | StudentName | varchar(20) | NO | | NULL | | +-------------+------------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec)