存储过程的优点
存储过程的创建
create procedure 存储过程名(参数)
存储过程体
编写一个存储过程,查询学生表中的所有信息。
delimiter $$
create procedure myproc1()
begin
select * form xs;
end $$
delimiter ;
执行:call myproc1();
参数
in :输入参数
out: 输出参数
inout:输入输出参数
要求:编写一个存储过程,通过学号查询某学生的信息。
delimiter $$
create procedure select_student(in xh char(6))
begin
select * from xs where 学号=xh;
end $$
delimiter ;
执行:call select_student('081101');
要求:编写一个存储过程,统计学生的总人数
delimiter $$
create procedure count_xs(out number int)
begin
select count(*) into number from xs;
end $$
delimiter ;
执行:call count_xs(@rs);
select @rs;
create procedure 存储过程名(in|out|inout 参数名 类型。。。。);
存钱 input(in a_id int,in money float)
表:id money
存储过程体:
1.局部变量
声明:declare 变量名 类型 [default 初始值]
declare num int default 0;
只能在begin 。。。end中声明。
2.赋值:set 变量名=值
set num=10;
3.select 。。。into 语句
4 流程控制
if语句
if 条件 then
语句
[elseif 条件 then 语句]
[else
语句]
end if
case语句
循环:
while 条件 do
循环体
end while
要求:编写存储过程,求1+2+3+4+。。。n
delimiter $$
create procedure myadd(in n int)
begin
declare i int default 1;
declare sum int default 0;
while i<=n do
set sum=sum+i;
set i=i+1;
end while;
select sum;
end $$
delimiter ;
delimiter $$
create procedure myadd(in n int,out s int)
begin
declare i int default 1;
set s=0;
while i<=n do
set s=s+i;
set i=i+1;
end while;
select s;
end $$
delimiter ;
执行:call myadd(100,@s);
select @s;
要求:创建一个account,有两个字段id,money
create table account
(id int not null primary key,
money int);
编写一个存储过程input,进行存钱
call input(账号,钱数);
首先判断前是否为负数,为负数,提示“钱不能为负数”,
如果>0
判断账号是否存在,如果不在,添加新记录
如果在,金额增加。
create procedure input(in aid int,in amoney int)
begin
if amoney<0 then
select '钱不能为负数';
elseif (select count(*) from account where id=aid)>0 then
update account set money=money+amoney where id=aid;
else
insert into account values(aid,amoney);
end if;
end
取钱 output
call output(1,100)