让我们先创建一张桌子
mysql> create table LimitWithStoredProcedure -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(10) -> );
使用insert命令在表中插入一些记录。
查询如下
mysql> insert into LimitWithStoredProcedure(Name) values('John'); mysql> insert into LimitWithStoredProcedure(Name) values('Chris'); mysql> insert into LimitWithStoredProcedure(Name) values('Maxwell'); mysql> insert into LimitWithStoredProcedure(Name) values('Bob'); mysql> insert into LimitWithStoredProcedure(Name) values('David'); mysql> insert into LimitWithStoredProcedure(Name) values('Carol'); mysql> insert into LimitWithStoredProcedure(Name) values('James'); mysql> insert into LimitWithStoredProcedure(Name) values('Jace'); mysql> insert into LimitWithStoredProcedure(Name) values('Robert'); mysql> insert into LimitWithStoredProcedure(Name) values('Mike'); mysql> insert into LimitWithStoredProcedure(Name) values('Sam'); mysql> insert into LimitWithStoredProcedure(Name) values('Peter'); mysql> insert into LimitWithStoredProcedure(Name) values('Ramit'); mysql> insert into LimitWithStoredProcedure(Name) values('Tony');
使用select语句显示表中的所有记录。
查询如下
mysql> select *from LimitWithStoredProcedure;
以下是输出
+----+---------+ | Id | Name | +----+---------+ | 1 | John | | 2 | Chris | | 3 | Maxwell | | 4 | Bob | | 5 | David | | 6 | Carol | | 7 | James | | 8 | Jace | | 9 | Robert | | 10 | Mike | | 11 | Sam | | 12 | Peter | | 13 | Ramit | | 14 | Tony | +----+---------+ 14 rows in set (0.00 sec)
这是您的存储过程,在LIMIT表达式中使用变量
mysql> DELIMITER // mysql> CREATE PROCEDURE Sp_limit(IN beg INTEGER, IN end INTEGER ) -> BEGIN -> PREPARE myStatement FROM -> "select *from LimitWithStoredProcedure LIMIT ?,? "; -> SET @beginning = beg; -> SET @ending = end ; -> EXECUTE myStatement USING @beginning, @ending; -> DEALLOCATE PREPARE myStatement; -> END // mysql> DELIMITER ;
借助CALL命令调用存储过程。
查询如下
mysql> call Sp_limit(4,7);
以下是输出
+----+--------+ | Id | Name | +----+--------+ | 5 | David | | 6 | Carol | | 7 | James | | 8 | Jace | | 9 | Robert | | 10 | Mike | | 11 | Sam | +----+--------+ 7 rows in set (0.00 sec)