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.表结构:

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.存储过程:

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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值