时间:2021-07-01 10:21:17 帮助过:24人阅读
调用:
call proc(@a, 2979);
取出变量a
SELECT @a;
ps:FOUND_ROWS()另一个技巧
可以使用SQL_CALC_FOUND_ROWS + LIMIT和FOUND_ROWS进行分页
SELECT SQL_CALC_FOUND_ROWS * FROM table_name LIMIT 10;
SELECT FOUND_ROWS();//这将返回上面查询的总记录数,不受limit影响
四.存储过程中的错误处理
如果语句块产生一个错误,该如何处理?是退出,还是继续?
1.语法:
DECLARE handler_action HANDLER FOR condition_value [, condition_value] ... statement handler_action: CONTINUE | EXIT | UNDO condition_value: mysql_error_code | SQLSTATE [VALUE] sqlstate_value | condition_name | SQLWARNING | NOT FOUND | SQLEXCEPTION
2.示例
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET a=-1;
如果执行sql语句时产生错误,将变量a设置为-1;如果没有产生错误,则保持原值
DELIMITER $$ CREATE PROCEDURE proc2(OUT a int(11)) LANGUAGE SQL NOT DETERMINISTIC CONTAINS SQL BEGIN DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET a=-1; SET @x=0; INSERT INTO test2(`time`) VALUES(10); END $$ DELIMITER ;
基本解释:mysql存储过程不支持为OUT和IN参数赋默认值,默认值即为null,null寓意不太明确,所以将a设置为0;如果你将
SET a=0;放在DECLARE CONTINUE HANDLER上面,将会引发一个错误.DECLARE CONTINUE HANDLER上面只可以再放置DECLARE定义的局部变量.放置set @x=10;等用户变量,也会引发一个错误.
五.游标
1.定义游标
DECLARE cursor_name CURSOR FOR select_statement
2.打开游标
OPEN cursor_name
3.FETCH 游标
FETCH cursor_name INTO var_name[,var_name]
4.关闭游标
CLOSE cursor_name;
5.示例:
DELIMITER $$
CREATE PROCEDURE proc3()
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
BEGIN
DECLARE myid INT;
DECLARE my_cursor CURSOR FOR (SELECT `id` FROM test2 ORDER BY `id` DESC);
DECLARE CONTINUE HANDLER FOR NOT FOUND CLOSE my_cursor;
OPEN my_cursor;
FETCH my_cursor INTO myid;
CLOSE my_cursor;
SELECT myid; #打印结果
END
$$
DELIMITER ;
ps:需要注意过程中的变量不要和查询语句中的字段名重名了,对字段名应该用``包裹.
由于以上没有用循环,所以只读取了一行就退出了.
六,循环
1.while循环
DELIMITER $$ CREATE PROCEDURE proc3() LANGUAGE SQL NOT DETERMINISTIC CONTAINS SQL BEGIN DECLARE myid INT; #定义变量 DECLARE my_cursor CURSOR FOR (SELECT `id` FROM test2 ORDER BY `id` DESC);#定义游标 DECLARE CONTINUE HANDLER FOR NOT FOUND SET myid=0;#如果没有数据的时候,将myis设置为0 OPEN my_cursor; #打开游标 FETCH my_cursor INTO myid;#获取一行数据 WHILE myid > 0 DO #while循环开始 SELECT myid; #打印结果 FETCH my_cursor INTO myid; #向下取一行数据 END WHILE; #结束循环标志 CLOSE my_cursor; #关闭游标 END $$ DELIMITER ;
2.LOOP循环:
DELIMITER $$ CREATE PROCEDURE proc5() LANGUAGE SQL NOT DETERMINISTIC CONTAINS SQL BEGIN DECLARE myid INT; #定义变量 DECLARE my_cursor CURSOR FOR (SELECT `id` FROM test2 ORDER BY `id` DESC);#定义游标 DECLARE CONTINUE HANDLER FOR NOT FOUND SET myid=0;#如果没有数据的时候,将myis设置为0 OPEN my_cursor; #打开游标 FETCH my_cursor INTO myid;#获取一行数据 ins : LOOP #ins为循环体名字 IF myid = 0 THEN #退出循环 LEAVE ins; #类似break END IF; IF myid = 2980 THEN ITERATE ins;#跳过当前循环,直接执行下一次循环 END IF; SELECT myid; FETCH my_cursor INTO myid; END LOOP ins; CLOSE my_cursor; #关闭游标 END $$ DELIMITER ;
3.repeat循环
略
MySQL存储过程和函数
标签:data pre 跳过 bre 表示 blog 否则 for 取出