mysql函数编写和存储过程

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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存储过程函数

mysql 存储过程入门

MySql存储过程与函数

mysql-存储过程和函数-热身运动

mysql编写存储过程

mysql使用navicat编写调用存储过程