mysql存储过程demo

以下为一个简单的存储过程的循环,当然自己是强烈不建议在存储过程中使用游标、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 THEN
    IF _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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大数据东哥(Aidon)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值