[MySQL光速入門]017 存儲過程當中的"異常處理"

異常處理

若是出現報錯了, 怎麼辦sql

擱在之前, 直接就停了post

有了異常處理, 咱們能夠選擇繼續仍是終止ui

create table test(id int);
create table test(id int);
select 1+1;
複製代碼

這段代碼會報錯(1050), 由於連續建立了兩個相同的表...spa

create table test(id int)
> 1050 - Table 'test' already exists
> 時間: 0.003s
複製代碼

因此select 1+1;不會執行, 咱們也看不到2...code

如今咱們有兩種選擇get

  1. 忽略錯誤, 繼續執行, 你會看到2
  2. 終止sql語句, 可是不要報錯

continue 跳過錯誤string

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();
複製代碼

也能夠簡寫it

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 終止程序io

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();
複製代碼

快速跳轉

相關文章
相關標籤/搜索