我写了一个存储过程,如下:
create procedure Proc_pro( a int,b int)
begin
   select * from table order by ID desc limit a,b;
end;
但是这样没办法运行,好想是limit后面不能跟变量。
不知道大家有没有遇到过这样的问题,或者有没有其他办法可以实现这个功能?

解决方案 »

  1.   

    limit只能传正整数进去,要写存储过程的话要用prepare语句才行.
    见下面的例子:
    mysql> select * from cc;
    +----+------+---------------------+
    | id | name | date                |
    +----+------+---------------------+
    |  1 | jim  | 2006-09-28 14:00:25 |
    |  2 | john | 2006-09-28 14:09:55 |
    +----+------+---------------------+
    2 rows in set (0.14 sec)
    mysql> create procedure test(a int ,b int)
        -> begin
        -> declare aa int default 0;
        -> declare bb int default 0;
        -> set @s='select * from cc limit ?,?';
        -> prepare stmt from @s;
        -> set @aa=a;
        -> set @bb=b;
        -> execute stmt using @aa,@bb;
        -> end;
        -> $$
    Query OK, 0 rows affected (0.03 sec)mysql> call test(1,1)$$
    +----+------+---------------------+
    | id | name | date                |
    +----+------+---------------------+
    |  2 | john | 2006-09-28 14:09:55 |
    +----+------+---------------------+
    1 row in set (0.09 sec)Query OK, 0 rows affected (0.09 sec)