MySQL的存储过程
存储过程是实现某个特定功能的sql语句的集合,编译后的存储过程会保存在数据库中,通过存储过程的名称可以反复的调用执行。
drop procedure if exists dcs30;#删除存储过程 如果存在dcs30
create procedure dcs30(i int) #创建存储过程,命名为dcs30
()=begin开始到 end结束里面的内容
(i int)==在创建存储过程时,可以在括号里面写入参数,这个参数叫做形式参数(形参)
注意:定义形参时,需要说明形参的数据类型
begin #开始
#写相关的SQL语句结合,需要重复执行的多条SQL语句
declare n int default (select count(*) from mm) ;
#定义一个变量n 类型为int,默认值为(统计mm表行数)
declare m int default '';
#定义一个变量m 类型为int,默认值为空
declare o int default(select max(score) from mm);
drop table if exists mm; #删除表 如果存在mm表
create table mm(id int(10) primary key auto_increment,score int(10))
insert into mm values(1,99),(2,88);
insert into mm values(3,97),(4,85);
insert into mm values(5,96),(6,86);
insert into mm values(7,95),(8,84);
select *from mm where id=j; 带参数的进行查询操作
select *from mm where id=i;
select *from mm; 不带参数地进行增删查改操作
select *from mm where id=3; 参数直接写死再整个存储过程里面
desc mm; 每次执行调用存储过程时,结果多少固定的
select *from mm where id=i; 形参是可以给SQL语句的集合去使用的
call dcs30(2,4)
存储过程定义形式参数,那么在调用时就要传入实际参数(实参),创建存储过程时定义多个形式参数,那么在调用存储过程时,就要定对应的传入多少个实际参数
在if判断语句中,有几个判断分支 if ,就有几个结束语 end if
if i=0 then
select count(*) from mm;
else if i>0 && i<=n then
select *from mm where id=i;
else if i>n then
while i>n do 10>8 条件满足的时候进入while循坏,条件不满足就退出while循坏
set o=o+1 ; 怎么让条件不满足?
insert into mm(score) values(o); 可以在while循坏里面设置结束循坏之前都设置一下条件的值+1(set n=n+1)
set n=n+1 ; while 条件do 之后需要 使用end while结束循坏判断
end while;
else
select *from mm;
end if;
end if;
end if;
|