功能:实现将表result_good_city_dzl中的字段lat更新为表 result_good_city_lh中的lat,条件是两个表中的id一样
即:
update result_good_city_dzl a set a.lat=(select lat from result_good_city_lh b where a.id=b.id and b.lat!=0)
DELIMITER $$
DROP PROCEDURE IF EXISTS update_result_good_city_dzl $$
CREATE PROCEDURE `update_result_good_city_dzl`()
BEGIN
DECLARE LhId BIGINT;
DECLARE Lhlat VARCHAR(40);
declare stop int default 0;
DECLARE cur CURSOR FOR (SELECT lat,id FROM result_good_city_lh);
/*
定义游标的结束,当遍历完成时,将stop设置为null
这里也可以写成 DECLARE CONTINUE HANDLER FOR NOT FOUND SET stop = null;
*/
declare CONTINUE HANDLER FOR SQLSTATE '02000' SET stop = null;
/*开游标*/
OPEN cur;
/*游标向下走一步,将查询出来的两个值付给定义的两个变量*/
FETCH cur INTO Lhlat,LhId;
/* 循环体 */
WHILE ( stop is not null) DO
/*更新数据表*/
update result_good_city_dzl set lat=Lhlat where id = LhId ;
/*游标向下走一步*/
FETCH cur INTO Lhlat,LhId;
END WHILE;
/*关闭游标*/
CLOSE cur;
END$$
DELIMITER ;
update_result_good_city_dzl();
执行存储过程(sql命令行执行)
CALL update_result_good_city_dzl();
/* Affected rows: 0 已找到记录: 0 警告: 0 持续时间 1 query: 1.014 sec. */
执行时间1秒多
方法2:
DELIMITER $$
DROP PROCEDURE IF EXISTS update_result_good_city_dzl $$
CREATE PROCEDURE update_result_good_city_dzl()
BEGIN
DECLARE LhId INT;
DECLARE Lhlat VARCHAR(40);
DECLARE done INT;
-- 定义游标
DECLARE rs_cursor CURSOR FOR
SELECT lat,id FROM result_good_city_lh;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
OPEN rs_cursor;
cursor_loop:LOOP
FETCH rs_cursor INTO Lhlat,LhId; -- 取数据
IF done=1 THEN
leave cursor_loop;
END IF;
-- 更新表
update result_good_city_dzl set lat=Lhlat where id = LhId ;
END LOOP cursor_loop;
CLOSE rs_cursor;
END$$
DELIMITER ;
执行存储过程(sql命令行执行)
CALL update_result_good_city_dzl();