如何创建一个SQL存储过程以插入多个值

时间:2019-01-12 21:55:49

标签: mysql sql stored-procedures amazon-rds

我有以下语句,该语句接受一组值并将它们存储在我的MySQL RDS中:

INSERT INTO items (item_id, item_name, item_description) VALUES ?

我将其与AWS Appsync一起使用,该工具没有提供防止注入的转义机制,因此,我想在RDS中使用存储过程来保护injection

此语句将用于创建多个项目,因此将传入一组值。

如何创建存储过程以将多个值插入表中?下面是一个带有单个参数的select语句的示例,但我不确定如何将其应用于上述参数中具有多个参数的更复杂的情况。

CREATE PROCEDURE listPets (IN type_param VARCHAR(200))
  BEGIN
     PREPARE stmt FROM 'SELECT * FROM Pets where type=?';
     SET @type = type_param;
     EXECUTE stmt USING @type;
     DEALLOCATE PREPARE stmt;
  END

2 个答案:

答案 0 :(得分:1)

CREATE PROCEDURE listPets (IN p_itemid INT, IN p_itemname VARCHAR(200), 
      IN p_itemdesc VARCHAR(200))
BEGIN
    PREPARE stmt FROM 'INSERT INTO items (item_id, item_name, item_description) VALUES (?, ?, ?)';
    SET @id = p_itemid, @name = p_itemname, @description = p_itemdesc;
    EXECUTE stmt USING @id, @name, @description;
    DEALLOCATE PREPARE stmt;
END

请参阅PREPAREEXECUTE上的文档。

提示:您可能想使用这种替代的INSERT语法:

PREPARE stmt FROM 'INSERT INTO items SET item_id=?, item_name=?, item_description=?';

这是MySQL对SQL的非标准扩展,它使匹配列和?占位符更加容易。但是它不支持多行插入。

答案 1 :(得分:0)

如果您要更新现有记录,则:

CREATE PROCEDURE LIST_Pets
(
    --These are the Variables/columns you need to enter data into to update
    @item_name VARCHAR(15),
    @item_description VARCHAR(30),

    --These are the variables used to get the correct record which needs update
    @item_id INT
)
AS
BEGIN
UPDATE TABLE type_param
SET item_name = ISNULL(item_name, @item_name)--if the item_name is null it will insert @item_name
SET item_description = ISNULL(item_description, @item_description)
WHERE item_id = @item_id