储存过程
关键字 procedure
例1
create procedure calssNo_10001()
select * from student
where ClassNo='10001';
例2
create procedure Student_ClassNo(CNo char(8))
select * from student
where ClassNo=CNo;
例3
create procedure ClassNo_Maxage(CNo char(8),out Maxage int)
set maxage =(select MAX(StudentAge) from Student
where ClassNo=Cno);
例2 和 例3 中的 CNo 和 Maxgae 都是类似于Java中的形式参数 与表中数据无关
表中并无CNo和Maxage列
例3中的out Maxage int
指的是定义一个输出的名叫Maxag的int类型的形式参数 并将学生表中的最高分数赋予Maxage 并输出Maxage
========================================================
调用储存过程
例1
call ClassNo_10001();
例2
call Student_ClassNo('10001');
例3
call ClassNo_Maxage('10001',@MA);//将学生表中的最高分数赋予Ma
select @MA; //查看MA
自定义函数
关键字 function
例
create function CalFinalScore
(x decimal(3,1),y decimal(3,1))
returns decimal(3,1)
return (x*0.3+y*0.3);
//(x decimal(3,1),y decimal(3,1)) 是定义x,y两个参数
// 注意 returns 后面加 返回的数据类型 ;
//return 加 返回的数据;
========================================================
调用自定义函数
set @a =(select UsuallyScore from Score where StudentNo='10403203'
and CourseNo='1001');
set @b =(select ExamScore from Score where StudentNo='10403203'
and CourseNo='1001');
select CalFinalScore(@a,@b);
//@a , @b 与 x ,y相对应 返回的值自然是(@a*0.3+@b*0.3)
流程控制
delimiter
详解
其实就是告诉mysql解释器,该段命令是否已经结束了,mysql是否可以执行了。
默认情况下,delimiter是分号;在命令行客户端中,如果有一行命令以分号结束,
那么回车后,mysql将会执行该命令。
但有时候,不希望MySQL这么做。在为可能输入较多的语句,且语句中包含有分号。 这种情况下,就需要事先把delimiter换成其它符号,如//、$$或者;;
分支语句 if-else
例
delimiter $$
create procedure MAX_Two(a int ,b int ,out max int)
begin
if a>b then
set max=a;
else
set max=b;
end if;
end$$
//注意 结束时 需要 end if ; 其他用法与Java中的if相同
分支语句 case
例
delimiter $$
create procedure Moment (out time varchar(4))
begin
declare sj int;
set sj =hour(now());
case
when sj>20&&sj<24 then set time ='晚上';
when sj>14&&sj<20 then set time ='下午';
when sj>12&&sj<14 then set time ='中午';
when sj>7&&sj<12 then set time ='上午';
when sj>0&&sj<7 then set time ='凌晨';
end case;
end$$
//注意 case when 以及结束时 end case
//declare sj int;指定义一个临时变量sj;
//set sj =hour(now());使将现在时间的小时赋予sj;
循环语句 while
例
delimiter $$
create procedure Summator(out sum int)
begin
declare i int;
set sum =0 ,i=1;
while i<=100 do
set sum=sum+1;
set i =i +1;
end while ;
end $$
//与Java中的while不同 需要while 条件 do 再加上循环体
触发器
创建触发器格式
create trigger 触发器名 触发时间 触法事件
on 表名 for each row
触发器动作
触发时间
after
先完成数据的修改 再触发
before
先触发 再进行数据的修改
触发事件
insert
将新行插入表时激活触发器
update
更改某一行时激活触发器
delete
从表中删除某一行时激活触发器
========================================================
例
创建after触发器
create trigger updateFor_Student
after update
on Student for each row
set @str='学生表信息被修改';
触发
update Student
set StudentAge=StudentAge+1
where StudentNo='10403201';
select @str;
两张特殊的临时表
new 表
储存着被 insert 和 update语句影响的新的数据行
old 表
储存着被 delete 和 update语句影响的旧数据行
========================================================
例
创建before触发器
delimiter $$
create trigger insert_Course
before insert
on Course for each row
begin
if new.CourseCredit>6 then
set new.CourseCredit=6;
end if;
end $$
触发
insert into course values(‘1006’,'大数据‘,8,’张三‘)$$