嵌套游标中的变量用法

时间:2019-07-01 09:10:12

标签: mysql stored-procedures cursor

我有一个这样的存储过程片段

 CREATE DEFINER=`root`@`%` PROCEDURE `new_procedure`()
    BEGIN
    DECLARE c_id varchar(100) DEFAULT "";
    DECLARE cursor1 CURSOR  for select id from t1 where name like 's%';
    OPEN cursor1;
    get_t1: LOOP
        FETCH cursor1 into c_id;
        p:begin
        declare cursor2 cursor for select id from t2 where cl_id=c_id;
        open cursor2;
        get_t2: loop
        fetch project_cursor into p_id;
                // perform some tasks
                t:begin
                  declare cursor3 cursor for select id from t3 where pr_id=p_id;
            open cursor3;
            get_t3:loop
                fetch cursor3 into t_id;
                IF v_finished = 1 THEN 
                LEAVE get_t3;
                END IF;
                //perform some tasks
            close cursor3;
            select p_id;
            end t;
end loop t2;    
    end p;
END LOOP t1;
END

此处select语句不显示任何数据

当我在光标3下写入select时,它正在工作。

我做错了吗?我错过的一切

1 个答案:

答案 0 :(得分:0)

您的SP中已经添加了一些基本逻辑,请尝试一下是否符合您的期望。

CREATE DEFINER=`root`@`%` PROCEDURE `new_procedure`()
BEGIN
    DECLARE c_id VARCHAR(100) DEFAULT "";
    DECLARE done1 BOOLEAN DEFAULT FALSE;
    DECLARE cursor1 CURSOR  FOR SELECT id FROM t1 WHERE name LIKE 's%';

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done1=TRUE; 

    OPEN cursor1;
    GET_T1: LOOP
        FETCH cursor1 INTO c_id;

        IF done1 THEN

            LEAVE GET_T1;

        END IF;

        P:BEGIN

        DECLARE p_id INT ; -- check which data types suits you, might be int
        DECLARE done2 BOOLEAN DEFAULT FALSE;

        DECLARE cursor2 CURSOR FOR SELECT id FROM t2 WHERE cl_id=c_id;

        DECLARE CONTINUE HANDLER FOR NOT FOUND SET done2=TRUE; 

        OPEN cursor2;
        GET_T2: LOOP

            FETCH cursor2 INTO p_id;

             IF done2 THEN

            LEAVE GET_T2;

            END IF;

        /* perform some task */

                T:BEGIN
                DECLARE t_id INT ; -- check which data types suits you, might be int
                DECLARE done3 BOOLEAN DEFAULT FALSE;

                DECLARE cursor3 CURSOR FOR SELECT id FROM t3 WHERE pr_id=p_id;

                DECLARE CONTINUE HANDLER FOR NOT FOUND SET done3=TRUE; 

                OPEN cursor3;
                GET_T3:LOOP

                    FETCH cursor3 INTO t_id;
                    IF done3 THEN 
                    LEAVE GET_T3;
                    END IF;
                    /* perform some tasks */

                    #select p_id;  -- don't know what you are doing with this 
                END LOOP GET_T3;
                CLOSE cursor3;
                SET done3=FALSE;
                END T;

        END LOOP GET_T2;   
        CLOSE cursor2;
        SET done2= FALSE;
        END P;

    END LOOP GET_T1;
    CLOSE cursor1;
    SET done1= FALSE;
END