MySQL遍历数据表是我们经常会遇到的问题,下面就为您详细介绍MySQL遍历数据表的方法,希望对您学习MySQL遍历数据表能有所帮助。
- DELIMITER $$
- USE `tns`$$
- DROP PROCEDURE IF EXISTS `MakeFriends`$$
- CREATE DEFINER=`root`@`localhost` PROCEDURE `MakeFriends`()
- BEGIN
- DECLARE v_adminId BIGINT(12);
- DECLARE v_currentUserID BIGINT(12);
- DECLARE v_ExistRela INT;
- DECLARE Done INT DEFAULT 0;
- DECLARE rs CURSOR FOR SELECT userId FROM hw_user;
- /* 异常处理 */
- DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET Done = 1;
- SET v_adminId = 1;
- /* 打开游标 */
- OPEN rs;
- /* 逐个取出当前记录userId字段的值*/
- FETCH NEXT FROM rs INTO v_currentUserID;
- /* 遍历数据表 */
- REPEAT
- IF NOT Done THEN
- SELECT COUNT(*) FROM hw_relationship WHERE sourceId = v_currentUserID AND targetId = v_adminId INTO v_ExistRela;
- /*SELECT v_currentUserID;SELECT v_ExistRela;*/
- IF v_currentUserID != v_adminId AND v_ExistRela = 0 THEN
- /* insert relation records*/
- INSERT INTO hw_relationship(createTime, relationType, sourceId, targetId) VALUES (NOW(), 1, v_currentUserID, v_adminId);
- INSERT INTO hw_relationship(createTime, relationType, sourceId, targetId) VALUES (NOW(), 1, v_adminId, v_currentUserID);
- END IF;
- END IF;
- FETCH NEXT FROM rs INTO v_currentUserID;
- UNTIL Done END REPEAT;
- /* 关闭游标 */
- CLOSE rs;
- END$$
- DELIMITER ;
【编辑推荐】