代码之家  ›  专栏  ›  技术社区  ›  Sagar Shinde

如何在mysql中使用存储过程参数在表中插入多行

  •  0
  • Sagar Shinde  · 技术社区  · 6 年前

    我有三张桌子的产品,尺寸和产品尺寸

    product 
     > id 
     > name
    product_size
     > product_id FK
     > size_id FK
    size
     > id
     > name
    

    知道使用存储过程我想插入多尺寸的单个产品 如。

    product.id =1;
    product.name = xyz;
    {
    product_size.product_id = 1
    product_size.size_id = 1
    product_size.product_id = 1
    product_size.size_id = 2
    product_size.product_id = 1
    product_size.size_id = 3
    }
    

    那么如何将size参数传递给mysql中的存储过程

    2 回复  |  直到 6 年前
        1
  •  0
  •   P.Salmon    6 年前

    如果要在插入件上附加所有尺寸的产品,则

    insert into product_size(product_id,size_id)
        select inprodid,name
        from size
        ;
    

    会的。 但是,如果只需要一些大小,那么可以将这些大小作为分隔字符串传递,并在包含insert语句的循环过程中拆分它们。如果使用google mysql拆分字符串,您将找到如何拆分字符串的示例。

        2
  •  0
  •   SeanW333    6 年前

    下面是一个存储过程,每次调用该过程时,都会将一条记录插入到产品大小中。该过程接受product.id和size.id的输入参数。

    DELIMITER //
    CREATE PROCEDURE INSERT_product_size(
                                        IN productID int, 
                                        IN sizeID int
                                        )
        BEGIN
            INSERT INTO 
                product_size
                    (product_id, size_id)
                VALUES
                    (productID, sizeID);
    
        END //
    DELIMITER ;
    

    此过程接受单个产品ID和大小ID的“数组”(以逗号分隔的字符串形式),并在一个过程调用中插入产品的所有大小:

    DROP PROCEDURE IF EXISTS INSERT_product_sizes;
    DELIMITER //
    CREATE PROCEDURE IF NOT EXISTS INSERT_product_sizes(
                                        IN productID int, 
                                        IN sizeIDs varchar(100)
                                        )
        BEGIN
    
            DECLARE delimiterCount int;
            DECLARE sizeID int;
            DECLARE loopCount int;
    
            /* Remove spaces, if any, from input string */
            SET sizeIDs = REPLACE(sizeIDs, ' ', '');
    
            /* Determine how many commas are in input string */
            SET delimiterCount = LENGTH(sizeIDs) - LENGTH(REPLACE(sizeIDs, ',', ''));
    
            SET loopCount = 1;
    
            /* For each id in input string */
            WHILE loopCount <= delimiterCount + 1 DO
                SET sizeID = SUBSTRING_INDEX(sizeIDs, ',', 1);
                INSERT INTO 
                    product_size
                        (product_id, size_id)
                    VALUES
                        (productID, sizeID);
                /* Remove last used id from input string */
                SET sizeIDs = REPLACE(sizeIDs, CONCAT(sizeID, ','), ''); 
                SET loopCount = loopCount + 1;
    
            END WHILE;
    
    
    
        END //
    DELIMITER ;