1

我有一个 MySql 函数,它接受 3 个参数。最后一个参数是一个查询本身,我可以使用 PREPARE(?) 执行它,至少在它没有多个结果的情况下是这样。我想遍历 PREPARED 语句返回的所有结果。

我怎样才能做到这一点?我正在考虑一个 CURSOR,但我能找到的是不可能在 PREPARED 变量语句上使用 CURSOR。

我想要实现以下目标: 1. 我在我的应用程序中查看结果。结果是分页的。2. 我想搜索一个特定的行,找到它所属的页面,并把它放到视图中。3.结果视图可以通过多种方式过滤和排序,因此MySql函数的第三个参数是查询结果视图填充。

希望我说清楚了,否则请告诉我。

到目前为止,我有以下内容:DELIMITER $$ # 否则你不能使用分号来结束一行

/*
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

提前致谢。

4

1 回答 1

2

将结果放入临时表中:

SET @sql := CONCAT('CREATE TEMPORARY TABLE tmp_GetPageForCowID ', SelectQuery);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

然后可以在临时表的内容上迭代游标。

于 2013-01-21T14:18:08.567 回答