1、函数
实际上就是一些功能模块,我们想要实现某个功能的话,就可以用这个模块,快速实现功能,系统中的函数不可能全部满足我们的需求
例子
要计算每个员工要交多少税。工资低于多少不用交税,每个人的都不同,如果要计算需要写一大堆的sql语句,为每个人计算的时候,都要重复的敲SQL命令
把这些sql语句写成一个函数(存储过程),重复性的调用这个存储过程,一个存储过程就是一个功能模块
语法
delimiter
create procedure x1()
begin
sql 语句;
end;
call x1();
有时候在调用存储过程的时候,需要输入不同的值,也就是根据不同的值来计算结果
drop procedure if exists x1; -- 如果该函数存在就把他删除
create procedure x1(in i int) -- in的意思是input输入,i是接受的变量,int是所接受变量的类型
begin
select i ;
end
call x1(4); -- 调用的时候加上参数
定义变量
set global xx=xx1; set @@xx=xx1; 系统变量
set @aa=1; 用户变量
set aa=1; declare aa=1; declare aa int default 0; 局部变量 --局部变量只在begin和end之间生效,在这之外就不生效了
2、如何使用常见的判断以及循环语句
2.1判断语句
if 判断1 then
SQL语句1;
elseif 判断2 then
SQL语句2;
elseif 判断3 then
SQL语句3;
.......
else
SQL语句n;
end if;
写一个存储过程,用来输入成绩,如果的输入的成绩大于等于100,则输入pass,否则输入
create procedure x1(name varchar(20),score int)
begin
if score<100 then
insert into student (name,'pass');
elseif score<100 then
insert into student (name,'pass');
end if;
end
类似于switch的语句
case xx
when 值1 then SQL语句1;
when 值2 then SQL语句2;
when 值3 then SQL语句3;
en case;
抽到的值为100奖100,200奖200
create procedure x1()
declare jl int default 0;
begin
case num
when 100 then select jl+100;
when 200 then select jl+200;
end case;
end
2.2循环语句
while 条件 do
SQL 语句
end while
如果条件为真,则重复执行do和end while之间的语句
drop procedure if exists x1;
create procedure x1()
begin
declare i int default 1;
while i<=10 do
insert into t_act values(i,i+1);
set i=i+1;
end while;
end
call x1();
repeat
repeat
SQL语句;
until 条件(注意:until这行后面是不能加分号的;否则会报错) 只要条件不成立就一直循环
end repeat;
drop procedure if exists x1;
create procedure x1()
begin
declare i int default 1;
repeat
insert into t_act value (i,i+1);
set i=i+1;
until i>10
end repeat;
end
call x1();
标签:loop
SQL语句;
if 条件 then
leave 标签;
end if;
end loop 标签;
loop自身是没有跳出循环的条件,如果想要跳出循环的换,要借助if,如果满足某种条件了,可以使用leave跳出
drop procedure if exists x1;
create procedure x1()
begin
declare i int default 1;
xx:loop
insert into t_act value (i,i+1);
set i=i+1;
if i>10 then
leave xx;
end if;
end loop;
end
call x1();
3、补充知识
show procedure status可以查看系统中有多少存储过程,\G在DOS窗口可查看详情
show create procedure 函数名:可以查看具体创建的命令
如果已经定义了一个存储过程,begin和end之间的内容是不能修改的,只能删除重建
drop procedure x1:删除一个存储过程
3.1实际使用
mysql的存储过程怎么给局部变量赋值数据库中查询的结果
drop procedure if exists x1;
create procedure x1()
begin
declare i int ;
SELECT count(*) into i from t_user where real_name='你好';
xx:loop
insert into t_act value (i,i+1);
set i=i+1;
if i>10 then
leave xx;
end if;
end loop;
end
call x1();
案例一
student表中部有三个字段id,name,score,老师输入学生的时候误操作,将小明输入了多次,请写出sql删除多余的小明,只保留一条有效数据
DROP PROCEDURE IF EXISTS x1;
CREATE PROCEDURE x1 ()
BEGIN
DECLARE x INT;
SELECT count(*) INTO x FROM student WHERE NAME = '小明' AND score= 23;
WHILE x > 1 do
delete FROM student WHERE NAME = '小明' LIMIT 1;
set x=x-1;
END WHILE;
END
call x1;