I have a MySql function, which takes in 3 arguments. The last argument is a query itself, which I can execute with PREPARE(?), at least if it does not have multiple results. I want to loop through all results returned from the PREPARED statement.
How can I do that? I was thinking of a CURSOR, but all I can find is that it is impossible to use CURSORs on a PREPARED variable statement.
What I want to achieve is the following: 1. I have a view of results in my application. The results are paged. 2. I want to search for a particular row, find the page it belongs on, and put it into view. 3. The view of results can be filtered and ordered in several ways, so therefore the third argument of the MySql function is the query the view of results is filled with.
Hopefully I made myself clear, otherwise let me know.
So far I have the following: DELIMITER $$ # Otherwise you cannot use semicolons to end a line
/*
The bar graph (clsBarGraph) shows cows in pages.
If you wish to search for a page with a certain Cow ID you need to do alot of things.
Therefore this function is created, to do the heavy lifting all in the database engine.accessible
@param LongCowID The long cow ID of the cow you wish to get the page for
@param ItemsPerPage To determine on what page a cow comes, it is necessary to known how many cows will fit into a page
@param SelectQuery The query that was used to view the data in the BarGraph. This determines ordering, which cows to have in the resultset to limit on, etc.
This should be without the limit
@return The page number to set the view to, or -1 if the cow does not exist.
*/
CREATE FUNCTION `GetPageForCowID`(LongCowID INT, ItemsPerPage INT, SelectQuery VARCHAR(255))
RETURNS INT
BEGIN
DECLARE `page` INT;
/* Prepares queries to execute */
PREPARE stmt_CheckIfCowExists FROM 'SELECT COUNT(`Long_Cow_ID`) as `rows` FROM `cow_data` INTO @NumberOfRows';
EXECUTE stmt_CheckIfCowExists;
IF @NumberOfRows = 1 THEN
/* The cow does nto exist */
SET `page` = -1;
ELSE
/* The cow does exist */
/* Get all the cows used in the view of the data, without a limit and put it into a variable */
SET @SelectQuery = CONCAT(@SelectQuery, ' INTO @CowsForDataView');
PREPARE stmt_SelectDataForView FROM @SelectQuery;
EXECUTE stmt_SelectDataForView;
SELECT COUNT(*) FROM stmt_SelectDataForView;
DEALLOCATE PREPARE stmt_SelectDataForView;
END if;
/* Clean Up */
deallocate PREPARE stmt_CheckIfCowExists;
return `page`;
END
thanks in advance.
Put the results into a temporary table:
SET @sql := CONCAT('CREATE TEMPORARY TABLE tmp_GetPageForCowID ', SelectQuery);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Then one can iterate a cursor over the content of the temporary table.