2013-02-21 56 views
0

我正在複製數據爲多對多關係表製作第三個表。 存儲過程目前看起來是這樣,但它有一些錯誤MySQL存儲過程嵌套遊標錯誤

DELIMITER $$ 
CREATE PROCEDURE `test`.UpdateRelatedAccounts() 
BEGIN 
    DECLARE ssn_sel_id VARCHAR(255) DEFAULT 0; 
    DECLARE id_sel_id CHAR(36) DEFAULT 0; 
    DECLARE id_sel_rel CHAR(36) DEFAULT 0; 
    DECLARE no_more_rows BOOLEAN; 
    DECLARE num_rows INT DEFAULT 0; 
    DECLARE no_more_rel_rows BOOLEAN; 
    DECLARE rel_num_rows INT DEFAULT 0; 

    DECLARE ssn_all_cur CURSOR FOR 
    SELECT ssn, id FROM ssn WHERE ssn NOT IN ('','000-00-0000'); 

    DECLARE ssn_cur CURSOR FOR 
    SELECT id FROM ssn WHERE id != id_sel_id AND ssn = ssn_sel_id; 

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rows = TRUE; 
-- DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rel_rows = TRUE; 



OPEN ssn_all_cur; 
SELECT FOUND_ROWS() INTO num_rows; 
    the_loop: LOOP 
     FETCH ssn_all_cur 
     INTO ssn_sel_id, id_sel_id; 

     IF no_more_rows THEN 
     CLOSE ssn_all_cur; 
     LEAVE the_loop; 
     END IF; 



    OPEN ssn_cur; 
    SELECT FOUND_ROWS() INTO rel_num_rows; 
    the_rel_loop: LOOP 
     FETCH ssn_cur 
     INTO id_sel_rel; 

     IF no_more_rel_rows THEN 
     CLOSE ssn_cur; 
     LEAVE the_rel_loop; 
     END IF; 

     INSERT INTO `ssn_related` (`ssn_primary`, `ssn_related`) VALUES (id_sel_id, id_sel_rel), (id_sel_rel, id_sel_id); 

    END LOOP the_rel_loop; 

    END LOOP the_loop;  
END$$ 
DELIMITER ; 

我怎麼巢使用的值,並插入到第三個表。

+0

確切地說,「它有一些錯誤」是什麼意思? – Bohemian 2013-02-21 11:38:47

+0

它不運行插入查詢,以便將所有相關記錄插入到表中 – HardCode 2013-02-21 11:59:12

回答

3

遊標緩慢,大部分時間不必要。嵌套遊標是慢速和不必要的。當真的沒有別的辦法時,遊標只能作爲最後的手段使用。

你想要做什麼可以細分到這一點:

INSERT INTO `ssn_related` (`ssn_primary`, `ssn_related`) 
SELECT 
ssn_1.id, 
ssn_2.id 
FROM 
ssn ssn_1 
INNER JOIN ssn ssn_2 ON ssn_2.ssn = ssn_1.id 
WHERE ssn_1.ssn NOT IN ('', '000-00-0000') 
AND ssn_2.id != ssn_1.id; 

然後你在SELECT交換柱再次這樣做。

INSERT INTO `ssn_related` (`ssn_primary`, `ssn_related`) 
SELECT 
ssn_2.id, 
ssn_1.id 
FROM 
ssn ssn_1 
INNER JOIN ssn ssn_2 ON ssn_2.ssn = ssn_1.id 
WHERE ssn_1.ssn NOT IN ('', '000-00-0000') 
AND ssn_2.id != ssn_1.id;