2013-06-12 39 views
5

此存儲過程我正在處理一些錯誤。我遇到了一個Result consisted of more than one row錯誤,但僅限於某些JOB_ID_INPUT值。我明白是什麼原因導致了這個錯誤,所以我試圖非常小心地確保我的返回值是標量。它很難看到存儲過程,所以我不確定哪裏可以產生錯誤。由於錯誤是有條件地拋出的,所以我認爲內存可能是一個問題,或者光標重用。我不經常使用遊標,所以我不確定。感謝任何有幫助的人。MySQL結果由存儲過程中的多行構成

DROP PROCEDURE IF EXISTS export_job_candidates; 
DELIMITER $$ 
CREATE PROCEDURE export_job_candidates (IN JOB_ID_INPUT INT(11)) 
BEGIN 

DECLARE candidate_count INT(11) DEFAULT 0; 
DECLARE candidate_id INT(11) DEFAULT 0; 

# these are the ib variables 
DECLARE _overall_score DECIMAL(5, 2) DEFAULT 0.0; 

# declare the cursor that will be needed for this SP 
DECLARE curs CURSOR FOR SELECT user_id FROM job_application WHERE job_id = JOB_ID_INPUT; 

# this table stores all of the data that will be returned from the various tables that will be joined together to build the final export 
CREATE TEMPORARY TABLE IF NOT EXISTS candidate_stats_temp_table (
    overall_score_ib DECIMAL(5, 2) DEFAULT 0.0 
) engine = memory; 

SELECT COUNT(job_application.id) INTO candidate_count FROM job_application WHERE job_id = JOB_ID_INPUT; 

OPEN curs; 

# loop controlling the insert of data into the temp table that is retuned by this function 
insert_loop: LOOP 

    # end the loop if there is no more computation that needs to be done 
    IF candidate_count = 0 THEN 
     LEAVE insert_loop; 
    END IF; 

    FETCH curs INTO candidate_id; 

    # get the ib data that may exist for this user 
    SELECT 
     tests.overall_score 
    INTO 
     _overall_score 
    FROM 
     tests 
    WHERE 
     user_id = candidate_id; 

    #build the insert for the table that is being constructed via this loop 
    INSERT INTO candidate_stats_temp_table (
     overall_score 
    ) VALUES (
     _overall_score 
    ); 

    SET candidate_count = candidate_count - 1; 

END LOOP; 

CLOSE curs; 

SELECT * FROM candidate_stats_temp_table WHERE 1; 

END $$ 
DELIMITER ; 

回答

4

WHERE 1(正如@cdonner所指出的)絕對看起來不正確,但我很確定發生了這個錯誤,因爲你的SELECT ... INTO命令之一返回了多行。

這一個應該是可以的,因爲它是一個總沒有GROUP BY,它總是返回一行:

SELECT COUNT(job_application.id) INTO candidate_count 
    FROM job_application WHERE job_id = JOB_ID_INPUT; 

因此它可能是這一個:

# get the ib data that may exist for this user 
SELECT 
    tests.overall_score 
INTO 
    _overall_score 
FROM 
    tests 
WHERE 
    user_id = candidate_id; 

揣摩,如果有可能對於此查詢返回多行,如果是這樣,你如何解決它。一種方法可能是MAX的總體分數:

SELECT MAX(tests.overall_sore) INTO _overall_score 
    FROM tests 
    WHERE user_id = candidate_id 
+0

這是一個問題,導致我的一個選擇...成爲需要極限情況的語句。謝謝。我一直盯着這個SP很長時間,以至於我忽略了那種簡單的東西。 – usumoio

4

我想你想使用

LIMIT 1 
在您選擇

,不

WHERE 1 

除了可以利用這個安全網,你應該明白你的數據找出你爲什麼得到多個結果。沒有看到數據,我很難猜測。