如下图所示,函数rand_name,过程insert_user;
-- 开启允许创建函数
set global log_bin_trust_function_creators = 1;
-- 创建随机生成姓名函数 rand_name
delimiter $$
create function rand_name(n int) returns varchar(16)
begin
-- 初始化一个16姓氏字符串,作为姓氏字符库
declare family_str varchar (128) default '赵钱孙李周吴郑王冯陈蒋沈韩杨朱秦';
-- 初始化一个32名字字符串,作为名字字符库
declare name_str varchar (128) default '平书文若山向秋凡白斌绮烟从蕾天曼润又亦从语绮彤之玉凡梅依琴沛槐敏';
-- 记录当前是第几个
declare i int default 0;
-- 记录生成结果
declare full_name varchar(16) default '';
-- 随机名字1、2位标记
declare rand_num int DEFAULT 0;
while i < n do
-- 若获取多个姓名,则用逗号','区分
set full_name = if(i > 0, concat(full_name, ','), full_name);
-- 随机取姓氏
set full_name = concat(full_name, SUBSTR(family_str, floor(1+rand()*16), 1));
-- 随机取名字
set full_name = concat(full_name, SUBSTR(name_str, floor(1+rand()*16), 1));
-- 名字是否为双字
set rand_num = rand()*10;
set full_name = if(rand_num > 5, concat(full_name, SUBSTR(name_str, floor(1+rand()*16), 1)), full_name);
set i = i + 1;
end while;
return full_name;
end$$
delimiter ;
-- 调用函数
select rand_name(1);
-- 创建测试表 study_user
create table study_user (
id int not null auto_increment ,
name varchar(16) default null,
age int default 0,
salary int default 0,
primary key (id)
) engine = innodb default charset = utf8
-- 创建新增测试数据存储过程 insert_user(max_num)
delimiter $$
create PROCEDURE insert_user(in num int)
begin
-- 记录循环次数
declare i int default 0;
-- 关闭自动提交
set autocommit = 0;
-- 循环insert
while i < num do
insert into study_user(name, age, salary) values
(rand_name(1), floor(15 + rand()*10), floor(rand()*10000 + rand()*1000));
set i = i + 1;
end while;
commit;
end$$
delimiter ;
-- 查询结果
call insert_user(100);
select * from study_user;