以下为一个简单的存储过程的循环,当然自己是强烈不建议在存储过程中使用游标、find_in_set()、not_find_in_set()之类的东东的,仅倒数据使用。
mysql 存储过程中常用的三种循环:while 、 loop 和 repeat
1、while循环语法:
while 表达式 do
end while;
2、repeat循环语法:
repeat
until 表达式
end repeat;
3、loop循环语法:
loop_lable:loop
if 表达式 then
leave loop_lable;
end if;
end loop;
以下写一个具体的批量导入数据的存储过程:
BEGIN
#申明要变量DECLARE _targetDes varchar(255) ;
DECLARE _targetPath longText;
DECLARE _targetPrice double ;
DECLARE _targetType int(11);
DECLARE _clothesId int(11);
DECLARE _secondLevelName varchar(255);
DECLARE _des varchar(255) ;
DECLARE tag INT default 0;
#申明游标
DECLARE cur_1 CURSOR FOR Select recommender.clothesId, recommender.targetType from recommender;
#定义游标是否继续执行状态码
DECLARE CONTINUE HANDLER FOR NOT FOUND SET tag = 1;
#打开已定义的游标
OPEN cur_1;
#定义循环语句开始,,存储过程循环大概有三种:
REPEAT
#遍历游标,并将遍历出来的值放入into 后面指定的字段中,,,注意:into后面的字段个数和类型都必须与申明游标时select查询字段个数和类型一样
fetch NEXT from cur_1 into _clothesId,_targetType;
#定义if 条件语句,必须有对应的end if 结束该判断
IF NOT tag THENIF _targetType = 1 THEN
update recommender set targetDes = (SELECT clothes.des from clothes where clothes.id = _clothesId ) , targetPath = (SELECT clothes.hangImage from clothes where clothes.id = _clothesId ) where recommender.clothesId = _clothesId ;
update recommender set targetId = _clothesId where recommender.clothesId = _clothesId;
# store price
select clothes.price into _targetPrice from clothes where clothes.id = _clothesId;
update recommender set targetPrice = _targetPrice where recommender.clothesId = _clothesId;
# store secondLevelName
select secondLevel.name into _secondLevelName from secondLevel where (secondLevel.id = (select clothes.secondLevelId from clothes where clothes.id = _clothesId ));
update recommender set targetSecondLevelName = _secondLevelName where recommender.clothesId = _clothesId ;
#与if对应的if结束语句
END IF;
END IF;
#repeat循环语句的条件语句,,表示除非条件满足,就不执行,否则继续循环 ,,类似do while() 循环语句
until tag
#对应的repeat结束语句
END REPEAT;
#关闭游标
CLOSE cur_1;
#提交,若不提交有可能写不进数据,,,最好申明事务,使用回滚来保持数据完整性, start transcation
commit;END