存储过程中在 LIMIT 表达式中使用变量?
让我们首先创建一个表
mysql> create table LimitWithStoredProcedure -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(10) -> ); Query OK, 0 rows affected (0.47 sec)
使用 insert 命令在表中插入一些记录。
查询如下:
mysql> insert into LimitWithStoredProcedure(Name) values('John'); Query OK, 1 row affected (0.15 sec) mysql> insert into LimitWithStoredProcedure(Name) values('Chris'); Query OK, 1 row affected (0.15 sec) mysql> insert into LimitWithStoredProcedure(Name) values('Maxwell'); Query OK, 1 row affected (0.28 sec) mysql> insert into LimitWithStoredProcedure(Name) values('Bob'); Query OK, 1 row affected (0.24 sec) mysql> insert into LimitWithStoredProcedure(Name) values('David'); Query OK, 1 row affected (0.20 sec) mysql> insert into LimitWithStoredProcedure(Name) values('Carol'); Query OK, 1 row affected (0.18 sec) mysql> insert into LimitWithStoredProcedure(Name) values('James'); Query OK, 1 row affected (0.29 sec) mysql> insert into LimitWithStoredProcedure(Name) values('Jace'); Query OK, 1 row affected (0.13 sec) mysql> insert into LimitWithStoredProcedure(Name) values('Robert'); Query OK, 1 row affected (0.20 sec) mysql> insert into LimitWithStoredProcedure(Name) values('Mike'); Query OK, 1 row affected (0.07 sec) mysql> insert into LimitWithStoredProcedure(Name) values('Sam'); Query OK, 1 row affected (0.25 sec) mysql> insert into LimitWithStoredProcedure(Name) values('Peter'); Query OK, 1 row affected (0.14 sec) mysql> insert into LimitWithStoredProcedure(Name) values('Ramit'); Query OK, 1 row affected (0.18 sec) mysql> insert into LimitWithStoredProcedure(Name) values('Tony'); Query OK, 1 row affected (0.16 sec)
使用 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 // Query OK, 0 rows affected (0.25 sec) 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) Query OK, 0 rows affected (0.03 sec)
广告