动态创建 MySQL 表的查询?
为此,可以使用存储过程。我们使用两个列动态创建一个表,即 StudentId 为 int,StudentName 为 varchar -
mysql> DELIMITER $$ mysql> 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 $$ Query OK, 0 rows affected (0.16 sec) mysql> DELIMITER ;
上面,我们将 StudentId 设为 PRIMARY KEY。
使用 CALL 命令调用存储过程 -
mysql> call creatingDynamicTableDemo('DemoTable'); Query OK, 0 rows affected, 1 warning (0.65 sec)
现在,您可以检查表的描述 -
mysql> 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)
广告