千山飘雪 2014-05-27 15:37
浏览 438
已采纳

mysql批量更新存储过程怎么写

我要写个存储过程,传入记录数N。
然后查找出按积分排序的前N条记录,然后循环设置记录的排名=i.
请问能给个demo么。

  • 写回答

4条回答 默认 最新

  • workaccoun 2014-05-27 17:42
    关注

    [code="java"]create procedure batchUpdate(in n int)
    begin
    declare inParam int default n;
    declare i int default 1;
    declare id int;
    declare username varchar(255);
    declare integral varchar(255);
    declare ranking int;
    declare _resultSet cursor for select a.id, a.username,a.integral,a.ranking from user a order by a.integral desc limit inParam;
    open _resultSet;
    while i <= inParam do
    fetch _resultSet into id, username, integral,ranking;
    update user a set a.ranking = i where a.id = id;
    set i = i +1;
    end while;
    close _resultSet;
    end;

    mysql> select * from user;
    +----+----------+----------+---------+
    | id | username | integral | ranking |
    +----+----------+----------+---------+
    | 1 | abc | 1 | 0 |
    | 2 | abc | 2 | 0 |
    | 3 | abc | 3 | 0 |
    | 4 | abc | 4 | 0 |
    | 5 | abc | 5 | 0 |
    | 6 | abc | 6 | 0 |
    | 7 | abc | 7 | 0 |
    | 8 | abc | 8 | 0 |
    | 9 | abc | 9 | 0 |
    | 10 | abc | 10 | 0 |
    | 11 | abc | 11 | 0 |
    | 12 | abc | 12 | 0 |
    | 13 | abc | 13 | 0 |
    | 14 | abc | 14 | 0 |
    +----+----------+----------+---------+
    14 rows in set

    mysql> call batchUpdate(14);
    Query OK, 1 row affected

    mysql> select * from user;
    +----+----------+----------+---------+
    | id | username | integral | ranking |
    +----+----------+----------+---------+
    | 1 | abc | 1 | 14 |
    | 2 | abc | 2 | 13 |
    | 3 | abc | 3 | 12 |
    | 4 | abc | 4 | 11 |
    | 5 | abc | 5 | 10 |
    | 6 | abc | 6 | 9 |
    | 7 | abc | 7 | 8 |
    | 8 | abc | 8 | 7 |
    | 9 | abc | 9 | 6 |
    | 10 | abc | 10 | 5 |
    | 11 | abc | 11 | 4 |
    | 12 | abc | 12 | 3 |
    | 13 | abc | 13 | 2 |
    | 14 | abc | 14 | 1 |
    +----+----------+----------+---------+
    14 rows in set[/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题