Mysql 存储过程

1.需求:

users表中的数据 如果在users_copy1表中存在(2各表id相等),则根据users表的数据更新users_copy1表的数据,这两个表id相等。

例子:

users表数据:

users_copy1表数据:

当执行完:CALL testproduce();后:

users_copy1后的表数据:

例子2:

users表数据:

users_copy1表数据:

当执行完:CALL testproduce();后:

users_copy1后的表数据:

2.表结构:

sql 复制代码
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

INSERT INTO `test`.`users_copy1` (`id`, `name`, `age`) VALUES (1, '张三', 10);
INSERT INTO `test`.`users_copy1` (`id`, `name`, `age`) VALUES (2, '李四', 20);
INSERT INTO `test`.`users_copy1` (`id`, `name`, `age`) VALUES (3, '王五', 30);



CREATE TABLE `users_copy1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

3.存储过程:

sql 复制代码
drop PROCEDURE if exists testproduce;

CREATE DEFINER=`root`@`%` PROCEDURE `testproduce`()
BEGIN
	#Routine body goes here...
  DECLARE s INT DEFAULT 0;
  DECLARE num INT DEFAULT 0;
  DECLARE ids INT DEFAULT 0;
  DECLARE names varchar(500) DEFAULT '';
  DECLARE ages INT DEFAULT 0;

	DECLARE list CURSOR FOR select id ids,name names,age ages from users;
	DECLARE CONTINUE HANDLER FOR SQLSTATE '02000'  set s=1;
	
	OPEN list;
  FETCH list into ids,names,ages;
	
	WHILE s <> 1 DO
		set num=(select count(1) counts from users_copy1 where id=ids);
		IF num =0 THEN 
		  
			insert into users_copy1 select id,name,age from users where id=ids;
				FETCH list into ids,names,ages;
		ELSE
		UPDATE users_copy1 set name=names,age=ages where id=ids; 
		  FETCH list into ids,names,ages;

		END IF;
		
	END WHILE;
	
	
CLOSE list;

END;
CALL testproduce();
相关推荐
NineData2 分钟前
NineData 亮相 2026 德国汉诺威工业博览会,加速拓展欧洲及全球市场
运维·数据库·人工智能·数据库管理·ninedata·ai服务·玖章算术
撩得Android一次心动2 分钟前
Android Room 数据库详解【源码篇】
android·数据库·android jetpack·room
m0_495496413 分钟前
C#怎么操作音频文件 C#如何用NAudio播放录制和处理WAV MP3音频文件【工具】
jvm·数据库·python
dFObBIMmai35 分钟前
CSS如何检测页面浮动元素位置_使用审查工具与clear
jvm·数据库·python
qq_4609784040 分钟前
实现 Svelte 中基于数组索引的 details 元素单开单关交互
jvm·数据库·python
这个DBA有点耶1 小时前
3步抓出慢SQL,别等半夜被叫醒😴
数据库·代码规范
dfdfadffa1 小时前
SQL窗口函数如何优化嵌套子查询_提升执行效率
jvm·数据库·python
m0_588758481 小时前
如何查看集群版本_crsctl query crs activeversion当前版本
jvm·数据库·python
摇滚侠2 小时前
Oracle19c 导出 Oracle11g 导入,Oracle19c 导出导入,Oracle11g 导出导入
java·数据库·oracle
zh1570232 小时前
CSS如何让元素出现时带抖动_利用关键帧定义抖动动画
jvm·数据库·python