Search code examples
mysqlcrudprocedure

Error while creating a procedure mysql CRUD


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`)
)

Solution

    • 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 ;