if ... end-if存储过程在mysql中出错

时间:2016-08-10 07:16:04

标签: mysql if-statement stored-procedures syntax-error

drop procedure if exists test;

delimiter $$
create procedure `test`() 
begin 
    DECLARE done INT DEFAULT FALSE;
    DECLARE i1 VARCHAR(20);
    DECLARE i2 DATE;
    DECLARE i3 VARCHAR(20);
    DECLARE i4 INT; 
    DECLARE curs1 CURSOR FOR SELECT * FROM test11;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    OPEN curs1; 
    FETCH curs1 INTO i1,i2,i3,i4;
    if i4=22 then
        insert into test1(abc) values(i1);
    end if ;
    CLOSE curs1; 
end ;

;;
delimiter ;
上面的

会引发错误:SQL Error [1064] [42000]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 14

create table test11(abc varchar(20), cde varchar(20), eg varchar(20), asda varchar(20));
insert into test11 values("Hello",'1989-08-09','sdads','22');

create table test1(abc varchar(20), cde int(20), eg date, asda varchar(20));

我不知道我做错了什么。语法似乎没问题。

drop procedure if exists sp;
CREATE PROCEDURE sp()
BEGIN
  DECLARE intoffer INT;
  SELECT max(asda) INTO intoffer FROM test11;
  IF (intoffer IS NULL) THEN
    SET intoffer = 1;
  ELSE
    SET intoffer = intoffer + 1;
  END IF;
  INSERT INTO test1 (asda) VALUES (intoffer);
end;

这是抛出相同错误的另一个过程。删除if..end之后 - 如果两个代码似乎都正常工作。

1 个答案:

答案 0 :(得分:0)

您遗失fetch from

drop procedure if exists test;

delimiter $$
create procedure `test`() 
begin 
    DECLARE done INT DEFAULT FALSE;
    DECLARE i1 VARCHAR(20);
    DECLARE i2 DATE;
    DECLARE i3 VARCHAR(20);
    DECLARE i4 INT; 
    DECLARE curs1 CURSOR FOR SELECT * FROM test11;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    OPEN curs1;
    insertLoop: LOOP 
    FETCH FROM curs1 INTO i1,i2,i3,i4;
    if i4=22 then
        insert into test1(abc) values(i1);
    end if ;
    END LOOP insertLoop;
    CLOSE curs1; 
end ;

;;
delimiter ;