MySQL stored procedure uses cursor set to update data [template]

Stored procedures are not used frequently, and are mainly used to update data content in batches. Here, record the template, and use it to modify it directly in the future.
This is relatively simple, mainly to traverse the result set and modify the content according to the conditions. There are detailed notes.

  1. Write the stored procedure, which is written in Navicat here, so there is no need to modify the end condition of sql.
  delimiter $$   //将结束符修改为$$  
  -- 存储过程结束的end后使用$$
  delimiter ;    //再改回来;


```sql
CREATE DEFINER=`root`@`localhost` PROCEDURE `template`()
BEGIN
-- 将maint表中的maint_mode根据apply_id同步到apply表
-- 	声明变量
	DECLARE s int DEFAULT 0; 
	DECLARE applyId BIGINT(20);
	DECLARE maintMode int(10);
-- 	将select语句查询的结果集赋值到maintCursor游标中
	DECLARE maintCursor CURSOR FOR SELECT apply_id,maint_mode from 		`process_maint_appro_maint`;
-- 	声明当前游标遍历结束后将标志变量设置为某个值
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET s=1;
-- 	打开游标
	OPEN maintCursor;
-- 			循环结束条件,上面游标的结束值为1时 结束循环
			WHILE s<>1 DO
			-- 		将游标的值赋给变量,变量名不要和返回的数据列名相同,要和结果集列的顺序一致
			FETCH maintCursor into applyId,maintMode;
-- 					所要执行的业务逻辑 更新字段内容
			update `process_maint_apply` set maint_mode=maintMode where id=applyId;
			END WHILE;
-- 			关闭游标
	CLOSE maintCursor;

	
END
  1. In the query, execute the stored procedure
call template();

Guess you like

Origin blog.csdn.net/chang100111/article/details/121419254