MySQL Forums
Forum List  »  Stored Procedures

Re: Variable in LIMIT clause
Posted by: Matthew Grdinic
Date: April 11, 2007 03:56PM

Per: William Chiquito http://forums.mysql.com/read.php?98,144558,144558#msg-144558

Passing dynamic variables in a stored procedure works per his example. I tired it out myself and all is well.

SAMPLE CODE (last two variables are the ones of interest):
IN model_1 varchar(40), IN model_2 varchar(40), IN model_3 varchar(40), IN filter varchar(20), IN p_low int, IN p_high int
)
BEGIN

IF model_1 = '' AND model_2 = '' AND model_3 = '' AND make_1 = '' AND make_2 = '' AND make_3 = '' THEN
SET @a = CONCAT('SELECT * FROM vehicleinventory ORDER BY ', filter, ' DESC LIMIT ', p_low, ',', p_high);
PREPARE stmtl FROM @a;
EXECUTE stmtl;
DEALLOCATE PREPARE stmtl;

You can also set variables as in:
IN model_1 varchar(40), IN model_2 varchar(40), IN model_3 varchar(40), IN filter varchar(20), IN p_low int, IN p_high int
)
BEGIN
SET @h = 10;

IF model_1 = '' AND model_2 = '' AND model_3 = '' AND make_1 = '' AND make_2 = '' AND make_3 = '' THEN
SET @a = CONCAT('SELECT * FROM vehicleinventory ORDER BY ', filter, ' ASC LIMIT ', @h, ',', p_high);
PREPARE stmtl FROM @a;
EXECUTE stmtl;
DEALLOCATE PREPARE stmtl;

Aslightly different syntax from the the MySQL manual: http://dev.mysql.com/doc/refman/5.0/en/select.html
For prepared statements, you can use placeholders (supported as of MySQL version 5.0.7). The following statements will return one row from the tbl table:

SET @a=1;
PREPARE STMT FROM 'SELECT * FROM tbl LIMIT ?';
EXECUTE STMT USING @a;

The following statements will return the second to sixth row from the tbl table:

SET @skip=1; SET @numrows=5;
PREPARE STMT FROM 'SELECT * FROM tbl LIMIT ?, ?';
EXECUTE STMT USING @skip, @numrows;


I am happy...for now : )



Edited 2 time(s). Last edit at 04/11/2007 04:06PM by Matthew Grdinic.

Options: ReplyQuote


Subject
Views
Written By
Posted
43816
June 01, 2005 07:13PM
18297
June 13, 2005 06:34PM
14501
July 12, 2005 03:59PM
12500
July 13, 2005 05:57PM
10631
July 13, 2005 05:58AM
10317
July 12, 2005 04:07PM
11956
July 15, 2005 05:37AM
8426
July 13, 2005 10:09AM
7802
July 15, 2005 05:45AM
8479
March 24, 2006 04:48PM
6441
June 15, 2006 07:23PM
6244
April 04, 2007 08:56PM
6598
April 11, 2007 01:07PM
Re: Variable in LIMIT clause
14752
April 11, 2007 03:56PM
6680
May 02, 2007 11:28AM
5753
March 16, 2009 05:58PM
6355
March 16, 2009 07:21PM
7718
April 29, 2009 05:31PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.