如何在 mySQL 过程中动态添加值?

How to dynamically add value in a mySQL procedure?

我有以下程序:

DROP PROCEDURE IF EXISTS insertCapacityIntoADay;
DELIMITER //
CREATE PROCEDURE insertCapacityIntoADay(startTime TIME, endTime TIME, capacity INT)
BEGIN
    INSERT INTO Capacities VALUES(UUID(), startTime, endTime, capacity;
END //
DELIMITER ; 

所以我可以这样使用它:

CALL insertCapacityIntoADay('00:00:00', '08:00:00', 120);

我的问题是,我如何定义我的过程,以便当我用多个 startTimeendTimecapacity 调用它时,它会多次添加值?即如果我这样做:

CALL insertCapacityIntoADay('00:00:00', '08:00:00', 120, '08:00:00', '20:00:00', 200, '20:00:00', '24:00:00', 150);

它应该等同于:

CALL insertCapacityIntoADay('00:00:00', '08:00:00', 120);
CALL insertCapacityIntoADay('08:00:00', '20:00:00', 200);
CALL insertCapacityIntoADay('20:00:00', '24:00:00', 150);

您可以使用 CSV 字符串模拟数组参数,有点像

CREATE PROCEDURE insertCapacityIntoADay(startTimes varchar(1000), endTimes varchar(1000), capacity varchar(1000))
...

CALL insertCapacityIntoADay('00:00:00, 08:00:00, 20:00:00', '08:00:00, 20:00:00, 24:00:00', '120, 200, 150')

在 proc 中创建一个循环来解析参数,并相应地发出 INSERT。

我想出了一个解决方案:

DROP PROCEDURE IF EXISTS insertCapacityIntoADay;
DELIMITER //
CREATE PROCEDURE insertCapacityIntoADay(capacities TEXT)
BEGIN
    DECLARE startTime VARCHAR(90);
    DECLARE endTime VARCHAR(90);
    DECLARE capacity VARCHAR(90);
    DECLARE maxIterations INT;
    DECLARE i INT;
    SET maxIterations = 3;
    SET i = 1;
    -- use a loop to insert values 3 times
    loop_label: LOOP
        IF i > maxIterations THEN
          LEAVE loop_label;
        END IF;
        -- separate values using comma
        SET startTime = (SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(capacities, ",", i), ',', -1));
        SET endTime = (SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(capacities, ",", i + 1), ',', -1));
        SET capacity = (SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(capacities, ",", i + 2), ',', -1));
        INSERT INTO Capacities VALUES(UUID(), startTime, endTime, capacity);
        SET i = i + 3;         
        ITERATE loop_label;
    END LOOP loop_label;
END//
DELIMITER ;

SET @capacity1= '00:00:00, 08:00:00, 80, 08:00:00, 15:00:00, 200, 15:00:00, 20:00:00, 150';
CALL insertCapacityIntoADay(@capacity1);