Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql, split a string and insert into table

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?

like image 476
Tausif Khan Avatar asked Oct 21 '11 06:10

Tausif Khan


2 Answers

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.

like image 177
Devart Avatar answered Oct 23 '22 04:10

Devart


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 ;
like image 5
Tom Mac Avatar answered Oct 23 '22 04:10

Tom Mac