Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored procedure, using variable in LIMIT expression

I have a stored procedure in which if I write the following query without a variable, all: works well

 CREATE PROCEDURE `some_proc` ()
 BEGIN
 SELECT blabla FROM  mytable ORDER BY id LIMIT 3,1
 .....

but, if I use a variable as start number in LIMIT expression, I get an error:

 CREATE PROCEDURE `some_proc` ()
 BEGIN
 DECLARE start INT;
 SET start = 3;
 SELECT blabla FROM  mytable ORDER BY id LIMIT start,1
 .....

Is there a way to use a variable in the LIMIT expression inside the stored procedure?

like image 575
ოთო შავაძე Avatar asked Jul 05 '12 11:07

ოთო შავაძე


People also ask

Can we use variable in limit in mysql?

Within stored programs, LIMIT parameters can be specified using integer-valued routine parameters or local variables.

Can we use variables in stored procedure?

A variable is a named data object whose value can change during the stored procedure execution. You typically use variables in stored procedures to hold immediate results. These variables are local to the stored procedure. Before using a variable, you must declare it.

Can stored procedures accept parameters?

You can also pass parameters to a stored procedure, so that the stored procedure can act based on the parameter value(s) that is passed.

How to set parameter value in SQL query?

When creating a procedure and declaring a parameter name, the parameter name must begin with a single @ character and must be unique in the scope of the procedure. If one parameter value is supplied in the form @parameter =value, all subsequent parameters must be supplied in this manner.


1 Answers

You cannot use a variable directly. A nice workaround that I've seen is -

CREATE PROCEDURE `some_proc` (
IN _START INTEGER, 
IN _LIMIT INTEGER 
)
BEGIN 
PREPARE STMT FROM 
" SELECT * FROM products LIMIT ?,? "; 
SET @START = _START; 
SET @LIMIT = _LIMIT; 
EXECUTE STMT USING @START, @LIMIT;
DEALLOCATE PREPARE STMT;
END $$ 

Another search returned this - http://bugs.mysql.com/bug.php?id=8094.

Also you can read more about prepared statements in the manual.

like image 79
FSP Avatar answered Oct 31 '22 16:10

FSP