栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

SQL-在MySQL中遍历表的每一行?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SQL-在MySQL中遍历表的每一行?

让我们看看我是否可以使用光标将您指向正确的方向:

delimiter $$create procedure findClosestTimeStamp()begin    -- Variables to hold values from the communications table    declare cFromId int;    declare cTimeStamp datetime;    -- Variables related to cursor:    --    1. 'done' will be used to check if all the rows in the cursor     --       have been read    --    2. 'curComm' will be the cursor: it will fetch each row    --    3. The 'continue' handler will update the 'done' variable    declare done int default false;    declare curComm cursor for        select fromId, timestamp from communication; -- This is the query used by the cursor.    declare continue handler for not found -- This handler will be executed if no row is found in the cursor (for example, if all rows have been read).        set done = true;    -- Open the cursor: This will put the cursor on the first row of its    -- rowset.    open curComm;    -- Begin the loop (that 'loop_comm' is a label for the loop)    loop_comm: loop        -- When you fetch a row from the cursor, the data from the current        -- row is read into the variables, and the cursor advances to the        -- next row. If there's no next row, the 'continue handler for not found'        -- will set the 'done' variable to 'TRUE'        fetch curComm into cFromId, cTimeStamp;        -- Exit the loop if you're done        if done then leave loop_comm;        end if;        -- Execute your desired query.        -- As an example, I'm putting a SELECt statement, but it may be        -- anything.        select *        from movement as m        where m.vID = cFromId and m.timeStamp <= cTimeStamp        order by timestampdiff(SECOND, cTimeStamp, m.timeStamp)        limit 1;    end loop;    -- Don't forget to close the cursor when you finish    close curComm;end $$delimiter ;

参考:

  • MySQL参考:游标
  • MySQL参考:日期和时间函数-
    timestampdiff()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/420142.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号