使用存储过程和游标
将user表的数据转移到new_user表
#将user表所有数据转移到new_user表中 DROP PROCEDURE IF EXISTS cursor_test; DELIMITER $ CREATE PROCEDURE cursor_test() BEGIN #声明user表存在的所有字段 DECLARE user_id INT; DECLARE user_code VARCHAR(32); DECLARE NAME VARCHAR(32); DECLARE username VARCHAR(100); DECLARE PASSWORD VARCHAR(100); DECLARE organization_id INT; DECLARE STATUS CHAR(1); DECLARE telephone VARCHAR(100); DECLARE remark VARCHAR(100); DECLARE is_delete CHAR(1); #声明user所有数据的数量,用于遍历的计数 记得要加()不然报错 DECLARE number INT DEFAULT (SELECT COUNT(*) FROM USER); #声明游标 user_result DECLARE user_result CURSOR FOR SELECT * FROM USER; #开启游标 OPEN user_result; WHILE number>0 DO #获取游标中一条数据
#注意:原表user中有的字段必须全部into去,不然掉用存储过程的时候会存在Incorrect number of FETCH variables错误 FETCH user_result INTO user_id,user_code,NAME,username,PASSWORD,organization_id,STATUS,telephone,remark,is_delete; #插入语句 INSERT INTO new_user (`user_id`, `user_code`, `name`, `username`, `password`, `telephone`) VALUES (user_id, user_code, NAME, username, PASSWORD, telephone); SET number = number-1; END WHILE; #关闭游标 CLOSE user_result; END $ DELIMITER;
创建new_user表
#创建需要转移数据的表new_user DROP TABLE IF EXISTS new_user; CREATE TABLE `new_user` ( `user_id` INT (11), `user_code` VARCHAR (100), `name` VARCHAR (100), `username` VARCHAR (100), `password` VARCHAR (100), `telephone` VARCHAR (11) );
执行
#调用存储过程cursor_test
CALL cursor_test;
#查询新表new_user
SELECT * FROM new_user;