共计 1154 个字符,预计需要花费 3 分钟才能阅读完成。
应用 procedure
批量建表。
有几点大家须要留神:
prepare_stmt
指令只能应用会话变量
来预筹备sql
,无奈应用declare
申明的局部变量
。procedure
中的创立的@会话变量
倡议做清理,防止会话变量净化。SET @foo = NULL;
即可。
DROP PROCEDURE IF EXISTS batchCreateTabPart;
DELIMITER $$
-- count 批量建表的数量
CREATE PROCEDURE batchCreateTabPart(IN count INT UNSIGNED)
BEGIN
-- 存储过程局部变量定义
DECLARE i INT UNSIGNED;
DECLARE suffix VARCHAR(8);
-- 局部变量初始化
SET i = 0;
SET suffix = "";
WHILE i < count DO
IF i < 10 THEN
SET suffix = CONCAT("0", i);
ELSE
SET suffix = i;
END IF;
SET @dropSql = CONCAT('DROP TABLE IF EXISTS `tb_part_', suffix, '`;');
PREPARE stmt FROM @dropSql;
EXECUTE stmt;
-- 拼接创立表 ddl
SET @createSql = CONCAT('CREATE TABLE IF NOT EXISTS `tb_part_', suffix, "`(
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(32) NOT NULL COMMENT '用户名',
`age` tinyint UNSIGNED NOT NULL DEFAULT 0 COMMENT '年龄',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='分示意例';");
PREPARE stmt FROM @createSql;
EXECUTE stmt;
SET i = i + 1;
END WHILE;
-- 删除过程中定义的用户会话变量
SET @dropSql = NULL;
SET @createSql = NULL;
END $$
DELIMITER ;
CALL batchCreateTabPart(100);
DROP PROCEDURE IF EXISTS batchCreateTabPart;
tab_part_00
tab_part_01
…tab_part_10
…tab_part_99
实现。
正文完