Error while creating a procedure mysql CRUD

本小妞迷上赌 提交于 2020-04-16 07:03:40

问题


I keep getting a syntax error at line 9

CREATE PROCEDURE `ItemsAddOrEdit`(
_itm_id INT,
_itm_name VARCHAR(255),
_itm_price FLOAT(8,2)
)
BEGIN
    IF _itm_id = 0 THEN
    INSERT INTO items (itm_name, itm_price)
    VALUES (_itm_name, _itm_price);
ELSE
    UPDATE items
    SET
        itm_name = _itm_name,
        itm_price = _itm_price
    WHERE itm_id = _itm_id;
END IF;
END

Are the variables the problem? I've checked the table to see if I messed the names up, but it all seems fine to me. Here's the table code

CREATE TABLE `items` (
`itm_id` INT(255) NOT NULL AUTO_INCREMENT,
`itm_name` VARCHAR(255) NOT NULL,
`itm_price` FLOAT(8,2) NOT NULL,
PRIMARY KEY (`itm_id`),
UNIQUE INDEX `itm_name` (`itm_name`)
)

回答1:


  • You need to redefine Delimiter to something else, for eg: $$. This allows parser to ignore ; (hence do not execute statement on reaching ;).
  • Also, as a good practice, always use DROP PROCEDURE IF EXISTS, to avoid failing out in case procedure with same name already exists.
  • At the end, redefine the Delimiter back to ;

Try the following:

DELIMITER $$

DROP PROCEDURE IF EXISTS `ItemsAddOrEdit` $$

CREATE PROCEDURE `ItemsAddOrEdit`(
_itm_id INT,
_itm_name VARCHAR(255),
_itm_price FLOAT(8,2)
)
BEGIN
    IF _itm_id = 0 THEN
    INSERT INTO items (itm_name, itm_price)
    VALUES (_itm_name, _itm_price);
ELSE
    UPDATE items
    SET
        itm_name = _itm_name,
        itm_price = _itm_price
    WHERE itm_id = _itm_id;
END IF;
END $$

DELIMITER ;


来源:https://stackoverflow.com/questions/52671758/error-while-creating-a-procedure-mysql-crud

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!