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
43592
June 01, 2005 07:13PM
18223
June 13, 2005 06:34PM
14448
July 12, 2005 03:59PM
12452
July 13, 2005 05:57PM
10582
July 13, 2005 05:58AM
10264
July 12, 2005 04:07PM
11907
July 15, 2005 05:37AM
8386
July 13, 2005 10:09AM
7749
July 15, 2005 05:45AM
8430
March 24, 2006 04:48PM
6399
June 15, 2006 07:23PM
6196
April 04, 2007 08:56PM
6546
April 11, 2007 01:07PM
Re: Variable in LIMIT clause
14699
April 11, 2007 03:56PM
6594
May 02, 2007 11:28AM
5712
March 16, 2009 05:58PM
6309
March 16, 2009 07:21PM
7661
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.