Erstellen cursor mit Dynamischem SQL in MYSQL

Schreibe ich eine gespeicherte Prozedur, die Sie öffnet einen cursor auf eine Tabelle und dann eine Iteration durch alle Einträge. In der Iteration Prozess erstelle ich eine dynamische Abfrage auf der Grundlage der Ergebnisse des ersten cursor. Ich brauche zu öffnen, den cursor auf dynamische sql, aber MySQL ist nicht so zu tun, mich so, wie accoriding zu den offiziellen doc von mysql "Cursor muss deklariert werden, bevor Sie deklarieren Handler. Variablen und Bedingungen müssen deklariert werden, bevor Sie deklarieren, entweder mit Cursor oder Handler". Hier ist das Skript

DELIMITER $$

DROP PROCEDURE IF EXISTS sp_test$$

CREATE PROCEDURE `sp_test`()
BEGIN
    -- Declarations

    DECLARE prepared_sql VARCHAR(1000);
    DECLARE index_count INT;

    -- Cursors
    DECLARE cursor1 CURSOR FOR SELECT * from table1;
    -- Continue Handler for Cursor
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rows = TRUE;
    -- Open cursors
    OPEN cursor1;

    -- Business Logic
    all_alerts_loop: LOOP
        -- Fetch record from cursor1 and create a dynamic sql

        -- Check if cursor has reached to end than leave the loop
        IF no_more_rows THEN
            LEAVE all_alerts_loop;
        END IF;


        WHILE @some_other_variable <> 0
        DO
                              -- I want to open cursor 2 on this sql
            -- set @prepared_sql =  'create dynamic sql here';  
                    END WHILE;

                    -- This works fine
        PREPARE stmt FROM @prepared_sql;
        EXECUTE stmt;

                    -- But can't define cursor here? so what is the solution
                    -- Gives syntax error, I have tried with @prepared_sql also rather than stmt
        DECLARE cursor2 CURSOR FOR stmt;

    END LOOP;

    -- closing cursors
    CLOSE cursor1;
    END$$

DELIMITER ;

Eine Idee, wie man erstellen Sie cursor für eine dynamische Abfrage? in MYSQL

InformationsquelleAutor Muhammad Ummar | 2011-05-21

Schreibe einen Kommentar