存储过程:
DELIMITER $$
USE `test`$$
DROP PROCEDURE IF EXISTS `UpdateRelatedAccounts`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `UpdateRelatedAccounts`()
BEGIN
DECLARE ssn_sel_id VARCHAR(255) DEFAULT 0;
DECLARE primary_sel_id CHAR(36) DEFAULT 0;
DECLARE secondary_sel_rel CHAR(36) DEFAULT 0;
DECLARE no_more_rows BOOLEAN;
DECLARE num_rows INT DEFAULT 0;
DECLARE ssn_all_cur CURSOR FOR
SELECT ac.ssn, ac.id AS primary_id, ac_b.id AS secondary_id FROM ssn ac LEFT JOIN ssn ac_b ON ac.ssn = ac_b.ssn WHERE ac.ssn NOT IN ('','000-00-0000') AND ac.id != ac_b.id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rows = TRUE;
OPEN ssn_all_cur;
SELECT FOUND_ROWS() INTO num_rows;
the_loop: LOOP
FETCH ssn_all_cur
INTO ssn_sel_id, primary_sel_id, secondary_sel_rel;
IF no_more_rows THEN
CLOSE ssn_all_cur;
LEAVE the_loop;
END IF;
INSERT INTO `ssn_related` ( `ssn_primary`, `ssn_related` ) VALUES ( '44','44'); -- ( primary_sel_id, secondary_sel_rel );
END LOOP the_loop;
END$$
DELIMITER ;
SSN表的结构是:
CREATE TABLE `ssn` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ssn` varchar(11) DEFAULT NULL,
`name` varchar(25) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;