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();
相关推荐
安审若无3 分钟前
图数据库neoj4安装部署使用
linux·运维·数据库
fenglllle27 分钟前
mybatis-plus SQL 注入漏洞导致版本升级引发的问题
数据库·sql·mybatis
learning-striving34 分钟前
SQL server创建数据表
数据库·sql·mysql·sql server
Yeats_Liao36 分钟前
时序数据库系列(三):InfluxDB数据写入Line Protocol详解
数据库·后端·时序数据库
天地之于壹炁兮1 小时前
编程I/O入门指南:核心操作全解析
数据库·windows·microsoft
切糕师学AI1 小时前
SQL中的函数索引/表达式索引
数据库·sql·mysql·postgresql·oracle
武子康1 小时前
Java-166 Neo4j 安装与最小闭环 | 10 分钟跑通 + 远程访问 Docker neo4j.conf
java·数据库·sql·docker·系统架构·nosql·neo4j
S_h_a_2 小时前
八股-Mysql 基础篇(1)
数据库·mysql
Dxy12393102162 小时前
MySQL的GROUP_CONCAT函数详解
数据库·mysql
编啊编程啊程2 小时前
【029】智能停车计费系统
java·数据库·spring boot·spring·spring cloud·kafka