如何在mysql 5存储过程中传递查询限制?

时间:2009-08-25 18:14:37

标签: sql mysql stored-procedures

以下是我想做的一个示例。 查询中存在LIMIT时,存储过程无法创建。 如果我关闭LIMIT,程序就会创建。

CREATE PROCEDURE LimitTest(IN in_start INTEGER UNSIGNED, IN in_limit INTEGER UNSIGNED)
BEGIN
   DECLARE no_more_results INTEGER DEFAULT 0;
   DECLARE var_result INTEGER UNSIGNED;
   DECLARE row CURSOR FOR SELECT id from test LIMIT in_start,in_limit;
   DECLARE CONTINUE HANDLER FOR NOT FOUND 
    SET no_more_results = 1;
   OPEN  row;
      FETCH  row INTO var_result;
      REPEAT 
         INSERT INTO results VALUES(var_result);
         FETCH  row INTO var_result;
      UNTIL no_more_results = 1
      END REPEAT;
   CLOSE row;
END

1 个答案:

答案 0 :(得分:3)

问题是,后面的数量限制必须是常量,并且不能是根据this bug report在MySQL的更高版本中保持不固定的参数。您可以尝试(丑陋的)解决方法outlined here: -

CREATE PROCEDURE sp (
IN LimitStart_ INT,
IN LimitCnt_ INT
)
BEGIN
SET @lim = CONCAT(' LIMIT ', LimitStart_, ',', LimitCnt_);
SET @q = "SELECT mycol FROM mytable";

SET @q = CONCAT(@q, @lim);
PREPARE st FROM @q;
EXECUTE st;
DEALLOCATE PREPARE st;
END;