views:

384

answers:

2

I have a procedure SelectProc wich contains SELECT statement. I want to add a procedure param LimitRowsCount and use it as following:

CREATE PROCEDURE SelectProc (IN LimitRowsCount INTEGER UNSIGNED) 
BEGIN
   SELECT (...)
   LIMIT LimitRowsCount;
END

but this approach doesn't work.

The SELECT itself contains nested subqueries so I can't create view from it. Is there a way more propper then dynamic SQL (prepared statements) ?

+2  A: 

From the manual:

The LIMIT clause can be used to constrain the number of rows 
returned by the SELECT statement. LIMIT takes one or two numeric 
arguments, which must both be nonnegative integer constants  
(except when using prepared statements). 

MySQL Manual - 12.2.8. SELECT Syntax

So that's a no - you cannot.

Martin
No means there is no better way? Nothing that works like LIMIT?
ssobczak
Nothing that is easier than using prepared statements. You could select your data into a temporary table, trim that to size, and select that - but that is a lot messier than just embedding a limit clause into a prepared statement. Is there any particular reason that you do not want to use prepared statements ?
Martin
I somehow just prefer not to use eval-like functions at all. In this case I will have to do so. Thanks for help!
ssobczak
You have to be careful of SQL injection - but if your eval / prepare is performed in a stored proc, you should be safe as long as your limit parameter is only a number. You should test the value within your stored proc for safety.
Martin
+2  A: 
CREATE PROCEDURE SelectProc (IN LimitRowsCount INT) 
BEGIN

SET @LimitRowsCount1=LimitRowsCount; 

PREPARE STMT FROM "SELECT (...) LIMIT ?";

EXECUTE STMT USING @LimitRowsCount1; 

END
Srinivas Tamada
http://forums.mysql.com/read.php?98,69465,78682
Babar