第17课 存储过程中的"异常处理"

异常处理

如果出现报错了, 怎么办

搁在以前, 直接就停了

有了异常处理, 我们可以选择继续还是终止

create table test(id int);
create table test(id int);
select 1+1;

这段代码会报错(1050), 因为连续创建了两个相同的表...

create table test(id int)
> 1050 - Table 'test' already exists
> 时间: 0.003s

所以select 1+1;不会执行, 我们也看不到2...

现在我们有两种选择

  1. 忽略错误, 继续执行, 你会看到2
  2. 终止sql语句, 但是不要报错

continue 跳过错误

drop PROCEDURE if EXISTS hello;

create procedure hello() begin 
declare existed condition for 1050;
declare continue handler for existed set @fail = 1;
create table teacher(id int);
select 1+1;
end;

call hello();

也可以简写

drop PROCEDURE if EXISTS hello;

create procedure hello() begin 
declare continue handler for 1050 set @fail = 1;
create table teacher(id int);
select 1+1;
end;

call hello();

exit 终止程序

drop PROCEDURE if EXISTS hello;

create procedure hello() begin 
declare existed condition for 1050;
declare exit handler for existed set @fail = 1;
create table teacher(id int);
select 1+1;
end;

call hello();

整行语句会因为重复建表而终止, 也不会输出2, 但是不会报错
也可以简写成

drop PROCEDURE if EXISTS hello;

create procedure hello() begin 
declare exit handler for 1050 set @fail = 1;
create table teacher(id int);
select 1+1;
end;

call hello();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容