【问题标题】:MySQL cursor fetch NULLMySQL游标获取NULL
【发布时间】:2017-04-01 09:05:38
【问题描述】:

为什么我的两个变量都输出NULLSELECT 部分光标工作正常。

CREATE PROCEDURE p2()
  BEGIN
    # Account table
    DECLARE accountid INT;
    DECLARE accountname VARCHAR(1000);

    # 1. cursor finished/done variable comes first
    DECLARE done INT DEFAULT 0;
    # 2. the curser declaration and select
    DECLARE c_account_id_name CURSOR FOR SELECT
                                           accountid,
                                           accountname
                                         FROM temp.test;
    # 3. the continue handler is defined last
    DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = TRUE;

    OPEN c_account_id_name;
    SET accountid = 0;
    SET accountname = '';

    read_loop: LOOP
      FETCH c_account_id_name
      INTO accountid, accountname;
      IF done
      THEN
        LEAVE read_loop;
      END IF;
      SELECT accountname;
    END LOOP;
  END;

【问题讨论】:

    标签: mysql database stored-procedures cursor


    【解决方案1】:

    游标中的变量和选择属性不能相同...这是一个 MySQL 错误。 这将起作用

    DROP PROCEDURE IF EXISTS p2;
    DELIMITER $$
    CREATE PROCEDURE p2()
      BEGIN
        # Account table
        DECLARE v_accountidsome INT;  #pay attention
        DECLARE v_accountnameelst VARCHAR(1000); #pay attention
    
        # 1. cursor finished/done variable comes first
        DECLARE v_done INT DEFAULT FALSE;
        # 2. the cursor declaration and select
        DECLARE c_account_id_name CURSOR FOR SELECT
                                               accountid, #pay attention
                                               accountname #pay attention
                                             FROM temp.test;
        # 3. the continue handler is defined last
        DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET v_done = TRUE;
    
        OPEN c_account_id_name;
    
        read_loop: LOOP
          FETCH c_account_id_name
          INTO v_accountidsome, v_accountnameelst;
          IF v_done
          THEN
            LEAVE read_loop;
          END IF;
          SELECT v_accountidsome;
          SELECT v_accountnameelst;
        END LOOP;
        CLOSE c_account_id_name;
      END $$
    DELIMITER ;
    
    CALL p2();
    

    了解更多here

    【讨论】:

    • 伟大的救生@D.R. !谢谢。
    • @NamGVU 没问题。如果您喜欢,请随意对问题本身进行升级:)
    • 谢谢@D.R.这拯救了我的一天!
    • @eRadical 非常欢迎你 :D 并毫不犹豫地支持这个问题 :)
    猜你喜欢
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    相关资源
    最近更新 更多