温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何理解MySQL的存储过程与光标

发布时间:2021-11-16 16:04:36 来源:亿速云 阅读:153 作者:柒染 栏目:MySQL数据库

今天就跟大家聊聊有关如何理解MySQL的存储过程与光标,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

MySQL的存储过程与光标

一、存储过程
T-sql 编程
增 删 改 查 —》语句
MySQL是一门真正语言 T-sql 类似于函数 function

1.存储过程:
创建格式:
create procedure 过程名称(参数1,参数2,…….)
begin
  sql代码
end
begin…and 就相当于以前{ 代码段 }
预编译,执行一次(编译),后边在使用直接调用编译结果 ,速度快

create procedure spade()
begin
select * from books;
end
//

mysql默认情况下遇到; 就执行了, ; 执行符号
在存储过程运行的时候delimiter符号修改执行符号

存储过程的调用:
call 过程名() //执行一次 (编译)

2、存储过程中的参数:
in 传入参数 把值传进去
out 传出参数 返回值
inout 传入传出参数 效率低下

in 输id是几查找第几条记录
create procedure one (in id int)
begin
select * from books where booksId=id;
end
//
call one(3);//

out 参数一个返回值
create procedure two (out spade int)
begin
select count(*) into spade from books;
end
//
注意:在sql 语句中赋值 into

在mysql 过程外边的变量 需要 @a
call thr(@a)//
select @a //查看变量
注意:
mysql中变量
过程外 @变量名称
过程内:声明
declare 变量名称 数据类型;

查找网站类型的图书
查找到类型的id
根据类型的id 在到图书表中 查找到对应的图书
create procedure toto()
begin
declare btid int;
set btid=(select cid from category where cName=”大事记”);
select * from category where cid=btid;
end
//

3、条件和处理程序
在某些条件下 执行某些程序
declare handler_type handler for conditionValue sq_statement

handler_type 操作类型
continue 继续
exit 退出
undo 忽略
conditionValue sql 错误的编号
02000 不正确的FETCH变量数目
23000 磁盘满了
sq_statement 执行对应的操作

declare continue handler for sqlstate “02000” set done=1;
当出现02000错误时候, 设置 done=1 后边程序继续执行

二、光标 抓取数据的
1、声明光标
declare 光标名称 cursor for sql语句 (select)

2、打开光标
open 光标名称

3、从光标中抓取数据
fetch 光表名称 into

4、关闭光标
close 光标名称
//抓取 btype中的数据
create procedure sex()
begin
declare id int;
declare name varchar(30);
declare done int default 0;
declare spade cursor for select * from books;
declare continue handler for sqlstate’02000’set done=1;
open spade;
repeat
fetch spade into id,name;
select id;
until done
end repeat;
close spade;
end
//
until false //终止条件不满足
until true 终止条件满足

补充:
if 条件 then
执行语句
else if 条件 then
执行语句
else if 条件 then
执行语句

else 以上条件都不满足
end if

mysql存储过程一般用来提高sql运行效率
php调用存储过程
create procedure getDate()
begin
select * from btype;
end

删除存储过程
drop procedure 过程名;

查看存储过程
show create procedure 过程名;

看完上述内容,你们对如何理解MySQL的存储过程与光标有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI