一, 游标
游标的使用主要包括四个步骤:
1) 申明游标 declare cursor_name for select statement;
2)打开游标 open cursor_name;
3)fetch 传递值 fetch cursor_name into param_list;
4)关闭游标 close cursor_name;
二 , 错误控制
DECLARE handler_type HANDLER FOR condition_value[,...] sp_statement
handler_type:
CONTINUE
| EXIT
| UNDO
condition_value:
SQLSTATE [VALUE] sqlstate_value
| condition_name
| SQLWARNING
| NOT FOUND
| SQLEXCEPTION
| mysql_error_code
请看如下实例:
创建table a1;
CREATE TABLE `a1` (
`id` int(11) DEFAULT NULL,
`name` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
创建table a2:
CREATE TABLE `a2` (
`id` int(11) DEFAULT NULL,
`name` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
将a1 的数据拷贝到a2的存储过程:
create procedure copy(IN a int)
BEGIN
#Routine body goes here...
declare b int;
declare c varchar(10);
declare d int;
declare c1 cursor for select * from kkk.a1;
declare exit handler for 1329
begin
insert into kkk.error_log(code,msg,time) values('1329','No data - zero rows fetched, selected, or processed',now());
end;
open c1;
set d=1;
repeat
fetch c1 into b,c;
insert into kkk.a2 values(b,c);
set d=d+1;
until a<d
end repeat;
close c1;
END
在这个例子中错误代码1329 表示没有数据,当a1为空时调用该存储过程,则会产生1329错误,此时将错误信息插入error_log表中。
a1中插入数据存储过程:
create procedure insertdata(IN a int)
BEGIN
#Routine body goes here...
declare b int default 1;
declare exit handler for SQLEXCEPTION
begin
insert into kkk.error_log(code,msg,time) values('00000','No data - zero rows fetched, selected, or processed',now());
end;
while b<=a
do
insert into kkk.a1 values(b,concat(b,'x'));
set b=b+1;
end while;
END