MySql, split a string and insert into table

后端 未结 4 587
再見小時候
再見小時候 2021-01-04 20:11

I have two inputs for my stored procedure. One is the \'RoledID\' and second one is the \'MenuIDs\'. \'MenusIDs\' is a list of comma separated menus ids that need to be inse

4条回答
  •  没有蜡笔的小新
    2021-01-04 20:40

    You can build one INSERT query (because statement allows to insert multiple records) and run it with prepared statements, e.g. -

    SET @MenuIDs = '1,2,3';
    SET @RoledID = 100;
    
    SET @values = REPLACE(@MenuIDs, ',', CONCAT(', ', @RoledID, '),('));
    SET @values = CONCAT('(', @values, ', ', @RoledID, ')'); -- This produces a string like this -> (1, 100),(2, 100),(3, 100)
    
    SET @insert = CONCAT('INSERT INTO RolesMenus VALUES', @values); -- Build INSERT statement like this -> INSERT INTO RolesMenus VALUES(1, 100),(2, 100),(3, 100)
    
    -- Execute INSERT statement
    PREPARE stmt FROM @insert;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    

    As you see, it can be done without stored procedure.

提交回复
热议问题