学习sql的存储过程,笔记总结如下:
MySQL默认将分号,即“;”作为语句的分隔符。如果是这样的话,则一个存储过程将很难正常创建,因为它的BEGIN和END之间可以是任意数量的SQL语句,而每条SQL语句都以分号结束。所以,在创建存储过程时,必须重新定义分隔符。在创建完存储过程后,必须重新设置回原来的分隔符“;”。
1. 创建普通存储过程的基本格式
--创建存储过程
DELIMITER $ --声明存储过程的结束符
create procedurepro_test()begin
--可以写多个sql
select * from admin where id = 1;select * from user limit 5;end $
2. 调用和删除存储过程
--调用存储过程
call pro_test();--删除存储过程
drop procedure pro_test; -- 注意:不是pro_test()
3. 存储过程的参数说明
IN:表示参数从外部传入到存储过程内部使用
OUT:表示参数从过程里边把数据保存到变量中,交给外部使用,所有传入的必须是变量。如果说传入的out变量本身在外部有数据,那么在进入过程之后,第一件事就是被清空,设为null
INOUT:数据可以从外部传入到过程内部使用,同事内部操作之后,又会将数据返回给外部。
4. 创建带有输入参数的存储过程
delimiter $create procedure pro_find(IN aid int)begin
select * from admin where id =aid;end$--调用
call pro_find(3);
5. 创建带有输出参数的存储过程
delimiter $create procedure pro_testout(out str varchar(20))begin
set str ="test out";end $
-- 调用
call pro_testout(@word);
-- 查看变量值
select @word;
6. 创建带有输入输出参数的存储过程
delimiter $create procedure pro_testinout(inout n int)begin
selectn ;set n = 500;end$--调用
set @n = 10;
call pro_testinout($n);--查看
select $n
7. 创建带有条件判断的存储过程
delimiter $create procedure pro_testif(in num int, out str varchar(20))begin
if num = 1 then
set str = '周一';
elseif num=2 then
set str = '';
elseif num= 3 then
set str = '';else
set str = '';end if;end$
call pro_testif(5, @str);select @str;
8. 创建带有循环功能的存储过程
delimiter $create procedure pro_testwhile(in num int, out result int)begin
declare i int default 1;declare vsum int default 0;while i <=num doset vsum = vsum +i;set i = i + 1;end while;set result =vsum;end$
call pro_testwhile(50, @result);select @result;
9. 使用查询结果赋值给变量(into)
delimiter $create PROCEDURE pro_find(in aid int, out uname varchar(20))begin
select username into uname from staff where id =aid;end$--调用
call pro_find(2, @name);select @name;
10. 删除存储过程
drop procedure pro_find;
11. 在thinkphp3中调用存储过程
query()执行的是查询(select)的SQL语句。
execute()执行的是插入(insert)和修改(update)的SQL语句。execute()方法将返回影响的记录数。
对于存储过程中,只有set语句时,需要使用M() -> execute($sql)来调用存储过程。
如果存储过程中,包含select语句是,可以使用execute或者query均可。