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();
相关推荐
Jabes.yang2 小时前
Java求职面试实战:从Spring Boot到微服务架构的技术探讨
java·数据库·spring boot·微服务·面试·消息队列·互联网大厂
阿巴~阿巴~3 小时前
Redis 核心文件、命令与操作指南
数据库·redis·缓存·客户端·服务端
koping_wu3 小时前
【Redis】用Redis实现分布式锁、乐观锁
数据库·redis·分布式
abcefg_h3 小时前
关系型数据库与非关系型数据库
数据库·nosql
海奥华24 小时前
SQLEXPLAIN 详解
数据库·mysql
00后程序员张4 小时前
【Python】基于 PyQt6 和 Conda 的 PyInstaller 打包工具
运维·服务器·数据库
huihuihuanhuan.xin4 小时前
后端八股之Redis
数据库·redis·缓存
情深不寿3174 小时前
MySQL————数据库基础
数据库·mysql
程序新视界4 小时前
如何选择合适的数据库?PostgreSQL与MySQL各项对比
数据库·mysql·postgresql
明月与玄武6 小时前
SQL核心语言详解:DQL、DML、DDL、DCL从入门到实践!
数据库·sql核心语言详解·dql、dml、ddl、dcl