2016-11-23 107 views
0

這裏是我的簡化,rent_ids字符串的值在循環後返回null。我已經知道循環運行正常,並且rent_id的值隨着每次啓動而改變。循環結束後變量的MySQL存儲過程值返回null

BEGIN 

DECLARE rent_ids VARCHAR(265); 
DECLARE tmp_rent_id int; 
create temporary table due_rent_ids (rent_id int); 
SET rent_ids = ""; 

set @test = "Insert into due_rent_ids (rent_id) select unit_id from tbl_rent"; 

PREPARE stmt1 FROM @test; 

EXECUTE stmt1; 

BEGIN 

     DECLARE cur1 CURSOR for select rent_id from due_rent_ids; 
     OPEN cur1; 

     read_loop: LOOP 
      FETCH cur1 INTO tmp_rent_id; 

      IF rent_ids = "" THEN 
       SET rent_ids = tmp_rent_id; 
      ELSE 
       SET rent_ids = concat(rent_ids, ", ", tmp_rent_id); 
      END IF; 

     END LOOP; 

     CLOSE cur1; 

END; 

select * from tbl_unit where unit_id in (rent_ids); 

DEALLOCATE PREPARE stmt1; 
END 
+0

爲什麼不直接使用'SELECT GROUP_CONCAT(rent_id)FROM due_rent_ids'? – Barmar

+0

'IN(rent_ids)'不會以逗號分割字符串。它只是尋找與整個字符串完全匹配的內容。 – Barmar

回答

0

你這樣做是錯的。您不能在IN (...)中放置逗號分隔的字符串,逗號必須位於實際的SQL代碼中。

做到這一點,正確的方法是:

SELECT * 
FROM tbl_unit 
WHERE unit_id IN (SELECT rent_id FROM due_rent_ids) 

或者:

SELECT t1.* 
FROM tbl_unit AS t1 
JOIN due_rent_ids AS t2 ON t1.unit_id = t2.rent_id 

第二種形式傾向於在MySQL中有更好的表現。

+0

謝謝。我開始循環嘗試從沒有臨時表的execute語句處理結果集,所以在添加臨時表之後,我沒有考慮其他選擇。 – zeina