简体   繁体   中英

Create stored procedure Insert and Update

I'm trying to insert and update queries at the same time in stored procedure, but I get a syntax error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '@product_id int(11), IN @ProductCode varchar(255), IN @ProductName varchar (2...' at line 1

This is my query here:

DELIMITER //
CREATE PROCEDURE UpdateProductList(IN @product_id int(11), IN @ProductCode varchar(255), IN @ProductName varchar (255), IN @PiecesInBox varchar (255), IN @Price varchar (255))
BEGIN
IF @product_id = 0
INSERT INTO products(ProductCode, ProductName, PiecesInBox, Price) VALUES(@ProductCode, @ProductName, @PiecesInBox, @Price);
ELSE
UPDATE products SET ProductCode = @ProductCode, ProductName = @ProductName, PiecesInBox = @PiecesInBox, Price = @Price WHERE product_id = @product_id;
END IF
END //
DELIMITER ;

Avoid using @ as they're reserved for global variables in MariaDB:

DELIMITER //
      
CREATE PROCEDURE UpdateProductList(
    IN in_product_id     INT(11),
    IN in_ProductCode    VARCHAR(255), 
    IN in_ProductName    VARCHAR(255), 
    IN in_PiecesInBox    VARCHAR(255), 
    IN in_Price          VARCHAR(255)
)
BEGIN
    IF in_product_id = 0 
    THEN INSERT INTO products(ProductCode, ProductName, PiecesInBox, Price) 
         VALUES (in_ProductCode, in_ProductName, in_PiecesInBox, in_Price);
    ELSE UPDATE products 
         SET ProductCode = in_ProductCode, 
             ProductName = in_ProductName, 
             PiecesInBox = in_PiecesInBox, 
             Price       = in_Price 
         WHERE product_id = in_product_id;
    END IF;
END //

DELIMITER ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM