【问题标题】:MySQL stored procedure value of variable returns to null after loop endsMySQL存储过程变量的值在循环结束后返回null
【发布时间】:2016-11-23 23:09:23
【问题描述】:

这是我的简化,rent_ids 字符串的值在循环后返回 null。我已经知道循环工作正常,并且rent_ids 的值随着每次迭代而变化。

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

【问题讨论】:

  • 你为什么不直接使用SELECT GROUP_CONCAT(rent_id) FROM due_rent_ids
  • IN (rent_ids) 不会以逗号分隔字符串。它只是寻找与整个字符串完全匹配的内容。

标签: mysql loops stored-procedures concatenation


【解决方案1】:

你做错了。不能在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 中表现更好。

【讨论】:

  • 谢谢。我开始循环尝试在没有临时表的情况下处理来自执行语句的结果集,所以在添加临时表后我没有考虑其他选择。
猜你喜欢
  • 2014-04-18
  • 2012-11-29
  • 2013-08-14
  • 1970-01-01
  • 2010-12-18
  • 2012-05-17
  • 1970-01-01
  • 1970-01-01
  • 2013-08-05
相关资源
最近更新 更多