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?
Within stored programs, LIMIT parameters can be specified using integer-valued routine parameters or local variables.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With