MYSQL 使用存儲過程批量更新表數據

功能:實現將表result_good_city_dzl中的字段lat更新爲表 result_good_city_lh中的lat,條件是兩個表中的id同樣sql

即:oop

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 ;code


update_result_good_city_dzl();blog

 

 執行存儲過程(sql命令行執行)ci

CALL update_result_good_city_dzl();

/* Affected rows: 0  已找到記錄: 0  警告: 0  持續時間 1 query: 1.014 sec. */it

執行時間1秒多class

 

方法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 ;date

 

 執行存儲過程(sql命令行執行)

CALL update_result_good_city_dzl();
相關文章
相關標籤/搜索