缺少SQL存储过程语法错误'结束'

时间:2015-04-29 17:34:15

标签: mysql sql stored-procedures

我一直在研究SQL存储过程,并且对这个过程很新。我正在尝试编写一个从一个表中检索值的过程,并将其作为新行的一部分插入到另一个表中。

我正在使用MySQL Workbench,它在行上给我一个错误

WHERE blockId = blk;

作为以下代码的一部分:

CREATE DEFINER=`root`@`localhost` PROCEDURE `add_userblock`(IN user INT(11), IN blk INT(11))
BEGIN
    -- Determine how many blocks you can add
    DECLARE blockNum INT DEFAULT -1;
    SELECT addCount INTO blockNum
        FROM block
        WHERE blockId = blk;

    -- Determine if the block already exists for the user
    DECLARE entryExists INT DEFAULT 0;
    SELECT COUNT(*) INTO entryExists
        FROM userblock
        WHERE blockId = blk AND userId = user;

    IF (entryExists = 0)
        -- This is a new entry
        BEGIN
        INSERT INTO userblock (userId, blockId, num) VALUES (user, blk, blockNum);
        SELECT LAST_INSERT_ID() as 'id';
        END
    ELSE
        -- This is an existing entry
        BEGIN
        UPDATE userblock
            SET num = (num + blockNum)
            WHERE userId = user AND blockId = blk;
        END
END

错误是"语法错误:缺少'结束'"。我不完全确定它意味着什么,而且我在解决这个问题上遇到了麻烦。

谢谢,我感谢你的时间!

1 个答案:

答案 0 :(得分:2)

END IF - 阻止

之后添加ELSE
CREATE 
DEFINER=`root`@`localhost` 
PROCEDURE `add_userblock`(
  IN user INT(11), 
  IN blk INT(11)
)
BEGIN
-- Determine how many blocks you can add
DECLARE blockNum INT DEFAULT -1;
SELECT addCount INTO blockNum
  FROM block
 WHERE blockId = blk;

-- Determine if the block already exists for the user
DECLARE entryExists INT DEFAULT 0;
SELECT COUNT(*) INTO entryExists
  FROM userblock
 WHERE blockId = blk
   AND userId = user;

IF (entryExists = 0)
    -- This is a new entry
    BEGIN
    INSERT INTO userblock (userId, blockId, num) VALUES (user, blk, blockNum);
    SELECT LAST_INSERT_ID() as 'id';
    END
ELSE
    -- This is an existing entry
    UPDATE userblock
       SET num = (num + blockNum)
     WHERE userId = user AND blockId = blk;
END IF
END