我会连续用一两个表,陆续出一些题目,同时也会给出答案,题目一般含有视图、触发器,函数,存储过程
存储过程例题:
同样是那个富豪榜,
当你传入参数为1和30时
存储过程会告诉小于三十岁的富豪有哪些
并把总人数存起来
当你传入参数为2时
会得到1000以内的所有水仙花数
提示:floor(a)取整,power(a,b)求a的b次方,select a输出a
语法:
#参数中in表示输入、out表示输出、
# inout表示可以输入可以输出
create procedure 存储过程名([参数列表])
begin
sql语句或者逻辑语句
end;
如果不了解语法的含义,看我的另一篇文章:
存储过程语法讲解
答案:
尽量自己做下^_^
创建富豪表
create table wealthy(
id int primary key auto_increment,
age int,
name varchar(20),
money int);
插入需要的数据
insert into wealthy values(1,20,'张三',110);
insert into wealthy values(2,35,'李四',110);
insert into wealthy values(3,35,'王五',90);
insert into wealthy values(4,20,'赵六',90);
创建平民表
create table person(
id int primary key auto_increment,
age int,
name varchar(20),
money int);
插入需要的数据
insert into person values(0,20,'十一',30);
创建存储过程
delimiter $$
create procedure pro_info(in p_in int,out p_out int,inout p_inout int)
begin
declare i int default 100;
if p_in=1 then
select p_in,p_out,p_inout;
select * from wealthy where age<p_inout;
select count(*) into p_out from wealthy;
set p_inout=p_inout*2;
set p_in=p_in*2;
select p_in,p_out,p_inout;
elseif p_in=2 then
while i<1000 do
if power(i%10,3) + power(floor(i/10)%10,3) + power(floor(i/100),3) =i then
select i;
end if;
set i =i+1;
end while;
end if;
end;
$$
delimiter ;
设置变量
p_in选择走那个if,p_out接收总个数,p_inout总条件
set @p_in=1,@p_out=-1,@p_inout=30;
调用存储过程
call pro_info(@p_in,@p_out,@p_inout);
再次查看变量,有何发现
select @p_in,@p_out,@p_inout;
查看水仙花数
call pro_info(2,@p_out,@p_inout);
查看存储过程
show create procedure pro_info \G;
show procedure status like '%pro%'\G;
删除存储过程
drop procedure pro_info;