Mysql 存储过程

时间:2024-10-01 22:15:53

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