--定义
CREATE PROCEDURE p1()
BEGIN
select count(*) from student;
END
--调用
call p1()
--查询存储过程
select * from information_schema.routineswhereroutine_schema='itcast';
show create procedure p1;
--删除
drop procedure if exists p1;
--命令行创建过程;分号是结束,替换一个可以完整结束的符号即可
delimiter $
CREATE PROCEDURE p1()
BEGIN
select count(*) from student;
END $
--查询系统变量
show global variables like 'auto%'
select @@session.autocommit;
--设置系统变量
set session autocommit=1;
--设置用户变量
set @myname :='itcast';
set @myage:=10;
set @mygender:='男',@myhobby:='java';
set @mycolor:='red';
select count(*) into @mycount from activity;
--使用用户变量
select @myname,@myage,@mygender,@myhobby;
--创建用户变量
create procedure p2()
begin
declare stu_count int default 0;
select count(*) into stu_count from student;
select stu_count;
end;
--存储过程定义
CREATE PROCEDURE `p3`(score int,out result varchar(10))
begin
if score>=85 then set result:='优秀';
elseif score>=60 then set result:='及格';
else set result:='不及格';
end if;
end;
--存储过程使用
call p3(89,@result);
select @result;
--存储过程定义
CREATE PROCEDURE p4(inout score double)
begin
set score:=score*0.5;
end;
--存储过程使用
set @score=100;
call p4(@score);
select @score;
--存储过程定义
CREATE DEFINER=`root`@`localhost` PROCEDURE `p5`(month int)
BEGIN
declare result varchar(10);
case
when month>=1 and month<=3 then
set result:='第一季度';
when month>=4 and month<=6 then
set result:='第二季度';
when month>=7 and month<=9 then
set result:='第三季度';
when month>=10 and month<=12 then
set result:='第四季度';
else
set result:='非法参数';
end case;
select concat(month,'月份',result);
END;
--存储过程使用
call p5(3);
--存储过程定义
create procedure p6(n int,inout sum int)
begin
while n>0 do
set sum:=sum+n;
set n=n-1;
end while;
end
--存储过程使用
set @sum=0;
call p6(2,@sum);
select @sum
--存储过程定义
CREATE PROCEDURE `p7`(n int)
begin
declare sum int;
set sum:=0;
repeat
set sum=sum+n;
set n=n-1;
until n<=0
end repeat;
select sum;
end
--存储过程使用
call p7(10)
--存储过程定义
CREATE PROCEDURE `p8`(n int)
begin
declare sum int default 0;
sum:loop
if n<=0 then
leave sum;
end if;
if n&1!=0 then
set n=n-1;
iterate sum;
end if;
set sum=sum+n;
set n=n-1;
end loop sum;
select sum;
end
--存储过程使用
call p8(10)