MySql, split a string and insert into table

2019-02-16 22:29发布

问题:

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 inserted with RoledID. RoleId is just an INT and we need to put this RoledID against each MenuID. My table 'RolesMenus' contains two columns one for MenuID and one for RoleID.

Now I need to split MenuIDs and insert each MenuID with RoleID.

How can I write a stored procedure for it?

回答1:

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.



回答2:

Give this a go. It may need some tweaking if the MenuIDs string does not conform to 'menuId,menuId,menuId'.

Also I do not know what data type the menuId column is in your target table (INT?) so you may have to put some numeric checking in too (in case '1,2,3,banana,4,5' is passed in as the MenuIds input parameter).

DELIMITER $$

DROP PROCEDURE IF EXISTS `insert_role_menuids`$$

CREATE PROCEDURE `insert_role_menuids`(IN RoleID INT,IN MenuIDs varchar(500))
BEGIN
declare idx,prev_idx int;
declare v_id varchar(10);

set idx := locate(',',MenuIDs,1);
set prev_idx := 1;

WHILE idx > 0 DO
 set v_id := substr(MenuIDs,prev_idx,idx-prev_idx);
 insert into RolesMenus (RoleId,MenuId) values (RoleID,v_id);
 set prev_idx := idx+1;
 set idx := locate(',',MenuIDs,prev_idx);
END WHILE;

set v_id := substr(MenuIDs,prev_idx);
insert into RolesMenus (RoleId,MenuId) values (RoleID,v_id);

END$$
DELIMITER ;


回答3:

AFAIK MySQL does not have a function to split strings. Here is the MySQL manual for string related functions. In the comments section should be some information about workarounds for splitting string with substring-functions but not really usable: MySQL manual