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
38170
June 01, 2005 07:13PM
17083
June 13, 2005 06:34PM
13776
July 12, 2005 03:59PM
11800
July 13, 2005 05:57PM
10037
July 13, 2005 05:58AM
9675
July 12, 2005 04:07PM
11212
July 15, 2005 05:37AM
7924
July 13, 2005 10:09AM
7205
July 15, 2005 05:45AM
7766
March 24, 2006 04:48PM
5869
June 15, 2006 07:23PM
5701
April 04, 2007 08:56PM
6089
April 11, 2007 01:07PM
Re: Variable in LIMIT clause
13831
April 11, 2007 03:56PM
6037
May 02, 2007 11:28AM
5110
March 16, 2009 05:58PM
5766
March 16, 2009 07:21PM
6927
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.