mysql程序使用游标

时间:2011-08-29 09:59:47

标签: mysql stored-procedures

DELIMITER $$

CREATE PROCEDURE INSERT_NONE_HISTORY_CHECKBOX()
BEGIN
  DECLARE note_id bigint(20);

  FOR c1 IN 
    (SELECT question_id 
     FROM question_master 
     WHERE question_type LIKE '%check box%') 
  LOOP

    SELECT note_section_id INTO note_id 
    FROM answer_master 
    WHERE question_id = c1.question_id 
    LIMIT 1;

    INSERT INTO answer_master(QUESTION_ID, NOTE_SECTION_ID, ANSWER_TEXT
      , ROS_INPUT_TEXT, HAS_CHILD_QUES, MEDICATIONS_LIST_ID, STATUS_CODE)
    VALUES(c1.question_id,note_id,'none',null,0,null,1);

  END LOOP;

END $$

DELIMITER ;

我收到像::

这样的错误
  

脚本行:3您的SQL语法有错误;检查与>您的MySQL服务器版本对应的手册,以便在'for c1 in'附近使用正确的语法(从question_master选择question_id>其中question_type如'%ch'在第6行

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我不认为MySQL支持FOR IN syntax你必须使用它来声明游标和循环。

DELIMITER $$

CREATE PROCEDURE INSERT_NONE_HISTORY_CHECKBOX()
BEGIN
  DECLARE note_id bigint(20);
  DECLARE Myquestion_id INTEGER;
  DECLARE done BOOLEAN DEFAULT 0; //loop variable
  DECLARE cur1 CURSOR FOR 
    SELECT question_id 
    FROM question_master 
    WHERE question_type LIKE '%check box%'; //declare the cursor
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;  //stop when done.

  OPEN cur1;  //Open it.
  insert_loop: LOOP

    FETCH cur1 INTO myquestion_id;
    IF done THEN LEAVE insert_loop; END IF;
    SELECT note_section_id INTO note_id 
    FROM answer_master 
    WHERE question_id = c1.question_id 
    LIMIT 1;

    INSERT INTO answer_master(QUESTION_ID, NOTE_SECTION_ID, ANSWER_TEXT
      , ROS_INPUT_TEXT, HAS_CHILD_QUES, MEDICATIONS_LIST_ID, STATUS_CODE)
    VALUES(myquestion_id,note_id,'none',null,0,null,1);

  END LOOP;
  CLOSE cur1;

END $$

DELIMITER ;

语法有点麻烦,但这应该有效。

请参阅:http://dev.mysql.com/doc/refman/5.0/en/cursors.html