I'm writing a stored function where I calculate the position of a cell, which value I need to select from a table. To do this, I decided to save this position in a variable, in order to use it as the offset of a LIMIT clause.
According to my research, the way of using values set into local variables with the LIMIT statement is through a prepared statement, but I also got that prepared statements (nor any dynamic SQL) are allowed in stored functions. Are there any alternatives to solve my problem?
A simplified example of my situation:
CREATE FUNCTION foo(a int) RETURNS decimal DETERMINISTIC
BEGIN
SET @var1 := (SELECT COUNT(*) FROM table);
SET @var2 := (ROUND(@var1 * a/5))
PREPARE STMT FROM 'RETURN (SELECT * FROM other_table LIMIT ?, ?)';
EXECUTE STMT USING @var2, @var1;
END
$$ DELIMITER ;
Ideally, this would get me the result I need, where I need it. But, of course, I get Error Code 1336 saying "Dynamic SQL is not allowed in stored function or trigger"