字符串参数拆分并插入MySQL中的列

时间:2014-10-20 10:46:46

标签: mysql stored-procedures split

如何在每列中插入带有特殊字符的分割字符串?

示例数据:

Firstname;Lastname;1985-04-01;2;a3;324;2020-01-01;2*Firstname2;Lastname2;1981-02-11;1;a3;324;2020-01-01;1*           

1 个答案:

答案 0 :(得分:0)

我已经用if条件解决了。

DELIMITER $$

CREATE DEFINER=`turerp_root`@`%` PROCEDURE `SAVE_RESERVATION`(IN paramGuestsInfo tinytext)
BEGIN
SET @guestCount = substrCount(paramGuestsInfo,'*')+1;
SET @v1=0;
SET @reservationId  = 1;

WHILE (@v1 < @guestCount) DO
    SET @guest = stringSplit(paramGuestsInfo,'*',@v1+1);
    SET @guestInfoCount = substrCount(@guest,';')+1;
    SET @v2=0;



    WHILE (@v2 < @guestInfoCount) DO

        SET @info = stringSplit(paramGuestsInfo,';',@v2+1);

            IF @v2 = 0
                THEN 
                    SET @firstName = @info;
            ELSEIF @v2 = 1
                THEN 
                    SET @lastName = @info;
            ELSEIF @v2 = 2
                            THEN 
                    SET @birthDate = @info;
            ELSEIF @v2 = 3
                            THEN
                    SET @gender = @info;
            ELSEIF @v2 = 4
                            THEN
                    SET @nationality = @info;
            ELSEIF @v2 = 5
                            THEN
                    SET @passportSerial = @info;
            ELSEIF @v2 = 6
                            THEN 
                    SET @passportNo = @info;
            ELSEIF @v2 = 7
                            THEN 
                    SET @passportExpire = @info;
        END IF;

        SET @v2 = @v2 + 1;
    END WHILE;
        INSERT INTO `turerp_db`.`reservation_guest`
        (`firstname`,
        `lastname`,
        `birthdate`,
        `gender_id`,
        `nationality_id`,
        `passport_serial`,
        `passport_no`,
        `passport_expire_date`)
        VALUES
        (@firstName,
         @lastName,
         @birthDate,
         @gender,
         @nationality,
         @passportSerial,
         @passportNo,
         @passportExpire);
    SET @guestId = LAST_INSERT_ID();
        INSERT INTO `turerp_db`.`reservation_has_guest`
        (`reservation_id`,
        `guest_id`)
        VALUES
        (@reservationId,
         @guestId);

    SET @v1 = @v1 + 1;
END WHILE;
END