美文网首页
第17课 存储过程中的"异常处理"

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

作者: 猫哥的技术博客 | 来源:发表于2019-04-09 19:10 被阅读0次

    异常处理

    如果出现报错了, 怎么办

    搁在以前, 直接就停了

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

    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();
    

    相关文章

      网友评论

          本文标题:第17课 存储过程中的"异常处理"

          本文链接:https://www.haomeiwen.com/subject/odzbiqtx.html