mysql 存储过程

delimiter //
drop procedure if exists test;
create procedure test()
begin
declare old_exp int; # 声明变量
declare temp_id int;
declare old_color int;
declare flag int default 0;
declare s_list cursor for select id,exp,color from hero; # 这是重点,定义一个游标来记录sql查询的结果
declare continue handler for not found set flag=1; # 为下面while循环建立一个退出标志,当游标遍历完后将flag的值设置为1
open s_list; # 打开游标
fetch s_list into temp_id, old_exp,old_color;
while flag <> 1 do
# sql提供了字符串的切分,有left、right、substring、substring_index
# 在T-SQL中,局部变量必须以@作为前缀,声明方式set,select还有点差别
#set @temp_s = substring_index(old_pro, "省", 1);
# 根据id的唯一性,利用当前查询到的记录中的字段值来实现更新

set @temp_c=concat('class',old_color);

set @exec_sql = concat('update hero set `level`= (select `heroLv` from exp_level where ',@temp_c , '> ',old_exp, ' limit 0,1 ) where id=',temp_id );
prepare _stmt from @exec_sql ;
execute _stmt;
deallocate prepare _stmt;

#@temp_s;
fetch s_list into temp_id, old_exp,old_color; # 游标往后移
end while;
close s_list; # 关闭游标
#select @temp_c,@temp_s;
end
//
delimiter ; # 重新定义;为一句sql的结束标志,取消//的所代表的意义
call test(); # 调用

 

#执行时 删除#后面的注释

posted @ 2020-05-08 18:08  boybai  阅读(150)  评论(0编辑  收藏  举报