建立部门表和员工表:
create table dept(
id int unsigned primary key auto_increment,
deptno mediumint unsigned not null default 0,
dname varchar(20) not null default "",
loc varchar(13) not null default ""
)ENGINE=INNODB DEFAULT CHARSET=GBK
create table emp(
id int unsigned primary key auto_increment,
empno mediumint unsigned not null default 0,
ename varchar(20) not null default "",
job varchar(9) not null default "",
mgr mediumint unsigned not null default 0,
hiredate date not null,
sal decimal(7,2) not null,
comm decimal(7,2) not null,
deptno mediumint unsigned not null default 0
)ENGINE=INNODB DEFAULT CHARSET=GBK
show variables like 'log_bin_trust_function_creators'
可以看到默认的二进制日志时关闭的
Variable_name |Value |
--------------------------------|------|
log_bin_trust_function_creators |OFF |
通过下面的命令进行临时设置:
set global log_bin_trust_function_creators=1
Variable_name |Value |
--------------------------------|------|
log_bin_trust_function_creators |ON |
DELIMITER $$
create FUNCTION rand_string(n int) returns varchar(255)
BEGIN
declare chars_str varchar(100) default 'abcdefghijklmnoprstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
declare return_str varchar(255) default '';
declare i int default 0;
while i
通过 DELIMITER
定义 mysql
语句的结束符,因为函数中多处有分号,如果不修改掉默认的结束符;那么函数将会产生错误
随后,创建生成随机数的函数:
delimiter $$
create function rand_num() RETURNS int(5)
begin
declare i int default 0;
set i=floor(100+rand()*10);
return i;
end $$
delimiter $$
create procedure insert_emp(IN START INT(10),IN max_num int(10))
begin
declare i int default 0;
set autocommit=0;
repeat
set i=i+1;
insert into emp(empno,ename,job,mgr,hiredate,sal,comm,deptno) values((start+i),rand_string(6),'SALESMAN',0001,CURDATE(),2000,400,rand_num());
until i=max_num
end repeat;
commit;
end $$
delimiter $$
create procedure insert_dept(IN START INT(10),IN max_num INT(10))
begin
declare i int default 0;
set autocommit=0;
repeat
set i=i+1;
insert into dept(deptno,dname,loc) values((start+i),rand_string(10),rand_string(8));
until i=max_num
end repeat;
commit;
end $$
# 在部门表中插入数据
call insert_dept(100,10);
+----+--------+------------+----------+
| id | deptno | dname | loc |
+----+--------+------------+----------+
| 1 | 101 | OVnDatOMsA | BbGYWOaO |
| 2 | 102 | PHQffkLYGl | mEgXmxza |
| 3 | 103 | IljlEhcRXn | xvJjUSGz |
| 4 | 104 | EwuFUElxBk | zNrtSdVl |
| 5 | 105 | vtHaksNIb | mdGUBVar |
| 6 | 106 | FamifbRZyr | ljmJDQso |
| 7 | 107 | tYLKrAAbHd | ziuuQRKZ |
| 8 | 108 | SpXNXzEvmc | ByJZUzNo |
| 9 | 109 | hXlpSoXPfj | HDUNcbT |
| 10 | 110 | sfBoRlLUlA | OtCCdPIU |
+----+--------+------------+----------+
# 在员工表中插入50W条数据,
mysql> call insert_emp(100001,500000);
这样就实现了大量数据的插入。
select `name` from mysql.proc where db = 'xx' and `type` = 'PROCEDURE' //存储过程
select `name` from mysql.proc where db = 'xx' and `type` = 'FUNCTION' //函数
show create procedure proc_name;
show create function func_name;