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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章