前言:
RAND函数,返回在范围0到1.0内的随机浮点值。如果一个整数参数N被指定,它被用作种子值。
一,朋友问题描述如下:
(1),有一个用户表,有id,用户的真实名字,年龄。
通过一段存储过程来实现向表里插入100数据,其中年龄随机
姓名
姓氏:’赵钱孙李周吴郑王’;,随机取出一个
名字:’一段文字字符串’,随机的取出一个字或者两个字
要求:随机的名字不能出现连续重复。
(2),然后我写出的代码如下:
-- 创建用户表,在project里
create table user1 (
id int not null primary key auto_increment,
name varchar(3) not null,
age tinyint not null
) charset utf8;
-- 创建存储过程
delimiter $$
create procedure pro3(num int)
begin
declare fname char(1);
declare name1 char(1);
declare name2 char(1);
declare fullname varchar(3);
declare age int;
declare i int default 1;
while i <=num do
set fname = substring('赵钱孙李周吴郑王',floor(1+8*rand()),1); -- 姓
set name1 = substring('一二三四五六七八九十甲乙丙丁',floor(1+14*rand()),1); -- 抽一个字
set name2 = substring('一二三四五六七八九十甲乙丙丁',floor(1+14*rand()),1); -- 抽一个字
if round(rand())=0 then -- 创造一个局部变量fullname代表全名,随机确定是两个字还是三个字
set fullname = concat(fname,name1);
end if;
if round(rand())=1 then
set fullname = concat(fname,name1,name2);
end if;
set age = floor(20+31*rand()); -- 年龄为2