将变量传递到CURSOR的SELECT查询(MySQL)

时间:2020-02-19 12:04:05

标签: mysql cursor

我正在尝试下面的存储过程。但是,当我在'DECLARE cur1'行中传递实际的列名时,SP返回正确的值,但是当我传递变量名即输入参数(colName)时,它返回0。我在下面的代码中添加了注释。代码正确吗?

DROP PROCEDURE IF EXISTS test1.checkHardcodedField;
CREATE PROCEDURE test1.checkHardcodedField(IN textValue CHAR(10), colName CHAR(10), OUT counter VARCHAR(100))
BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE temp CHAR(16);
  DECLARE i INT DEFAULT 0;

  -- Issue with this statement, returns incorrect value.
  DECLARE cur1 CURSOR FOR SELECT colName FROM data1;   

  -- This statement works. MSH3 is actual column name
  -- DECLARE cur1 CURSOR FOR SELECT MSH3 FROM data1; 

  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN cur1;

  read_loop: LOOP
    FETCH cur1 INTO temp;

    IF done THEN
      LEAVE read_loop;
    END IF;
    IF temp = textValue THEN
      SET i = i + 1;
    END IF;
  END LOOP;

  SET counter = i;

  CLOSE cur1;
END;

1 个答案:

答案 0 :(得分:0)

False