1

私はMySql関数を持っています。これは3つの引数を取ります。最後の引数はクエリ自体であり、少なくとも複数の結果がない場合は、PREPARE(?)を使用して実行できます。PREPAREDステートメントから返されたすべての結果をループしたいと思います。

どうやってやるの?私はCURSORについて考えていましたが、PREPARED変数ステートメントでCURSORを使用することは不可能であることがわかりました。

私が達成したいのは次のとおりです。1。アプリケーションの結果を表示します。結果はページングされます。2.特定の行を検索し、それが属するページを見つけて、それを表示したいと思います。3.結果のビューはいくつかの方法でフィルタリングおよび順序付けできるため、MySql関数の3番目の引数は、結果のビューが入力されるクエリです。

うまくいけば、私は自分自身を明確にしました、そうでなければ私に知らせてください。

これまでのところ、次のようになっています。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 に答える