码迷,mamicode.com
首页 > 数据库 > 详细

mysql函数编写和存储过程

时间:2016-04-04 21:10:43      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:存储过程   函数   mysql   

#建表

#创建表CLASS

CREATE TABLE classes( /*班级表*/

classno MEDIUMINT   UNSIGNED  NOT NULL  DEFAULT 0,

classname VARCHAR(20)  NOT NULL  DEFAULT "",

loc VARCHAR(13) NOT NULL DEFAULT ""

) ENGINE=innodb DEFAULT CHARSET=utf8;


#创建表STUDENTS学生表

CREATE TABLE students

(studentno  MEDIUMINT UNSIGNED  NOT NULL  DEFAULT 0,

studentname 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,

classno MEDIUMINT UNSIGNED NOT NULL DEFAULT 0

)ENGINE=innodb DEFAULT CHARSET=utf8 ;


#学生薪水级别表(1-5000,2-5000-8000 3-8000+)

CREATE TABLE salgrade

(

grade MEDIUMINT UNSIGNED NOT NULL DEFAULT 0,

losal DECIMAL(17,2)  NOT NULL,

hisal DECIMAL(17,2)  NOT NULL

)ENGINE=innodb DEFAULT CHARSET=utf8;


INSERT INTO salgrade VALUES (1,1500,5000);

INSERT INTO salgrade VALUES (2,5001,8000);

INSERT INTO salgrade VALUES (3,8001,12000);

INSERT INTO salgrade VALUES (4,12001,15000);

INSERT INTO salgrade VALUES (5,15001,59999);



#创建一个随机产生字符串的函数:

create function rand_string(n INT)

returns varchar(255)

deterministic

begin

declare chars_str varchar(100) default

‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ‘;

declare return_str varchar(255) default ‘‘;

declare i int default 0;

while i<n do

set return_str = concat(return_str,substring(chars_str,floor(1+rand()*52),1));

set i = i + 1;

end while;

return return_str;

end ||


#创建一个随机产生的数字

create function rand_num(n INT)

returns int(5)

deterministic

begin

declare i int default 0;

set i = floor(1+rand()*n);

return i;

end ||



#存储过程:

#插入学生

create procedure insert_students(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 students values((start+i),rand_string(6),‘salesman‘,0001,curdate(),2000,400,rand_num(500));

until i = max_num

end repeat;

commit;

end ||


#插入班级

create procedure insert_class(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 class values((start+i),rand_string(10),rand_string(8));

until i = max_num

end repeat;

commit;

end ||


mysql函数编写和存储过程

标签:存储过程   函数   mysql   

原文地址:http://1150895809.blog.51cto.com/9164250/1760156

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!