2

I have create a mysql Procedure. here its code

BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE a , b, d TEXT;
  DECLARE c INT Default 0;
  DECLARE cur1 CURSOR FOR SELECT id, school_id  FROM my_list;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
  OPEN cur1;
  read_loop: LOOP
    FETCH cur1 INTO a, b;
    IF done THEN
      LEAVE read_loop;
    END IF;
     insertSchool: LOOP  
         SET c = c + 1;
         d = SUBSTRING_INDEX(b, ',', c);
       IF d = "" THEN
          LEAVE insertSchool;
       END IF;      
        INSERT INTO my_school (my_id, school_id) VALUES (a,b);
    END LOOP insertSchool;
  END LOOP;
  CLOSE cur1;
END

In this cur1 has school_id as string it contain school ids in comma separated. i want split these ids and store in different table. but this line d = SUBSTRING_INDEX(b, ',', c); shows the error. can anyone please provide solution how to use SUBSTRING_INDEX in procedure?

naveen goyal
  • 4,571
  • 2
  • 16
  • 26
  • This is very similar to http://stackoverflow.com/questions/5928599/equivalent-of-explode-to-work-with-strings-in-mysql – noz Aug 09 '13 at 05:35

1 Answers1

5

Your immediate problem is not with SUBSTRING_INDEX but rather with missing SET

Change

d = SUBSTRING_INDEX(b, ',', c);

to

SET d = SUBSTRING_INDEX(b, ',', c);
^^^


Now that will solve syntax error but you need to make quite a few changes to your code to make it work.

To get n-th element from a list you need to apply SUBSTRING_INDEX() twice

SUBSTRING_INDEX(SUBSTRING_INDEX(list, ',', n), ',', -1)

That being said your SP might look like

DELIMITER $$
CREATE PROCEDURE my_sp()
BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE a, b, d VARCHAR(12);
  DECLARE c, m INT DEFAULT 0;

  DECLARE cur1 CURSOR FOR SELECT id, school_id  FROM my_list;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN cur1;

  read_loop: LOOP
    FETCH cur1 INTO a, b;
    IF done THEN LEAVE read_loop; END IF;
    SET c = 0;
    SET m = CHAR_LENGTH(b) - CHAR_LENGTH(REPLACE(b, ',', ''));

    insertSchool: LOOP
       SET c = c + 1;
       IF c > m + 1 THEN LEAVE insertSchool; END IF;
       SET d = SUBSTRING_INDEX(SUBSTRING_INDEX(b, ',', c), ',', -1);
       INSERT INTO my_school (my_id, school_id) VALUES (a, d);
    END LOOP insertSchool;

  END LOOP;
  CLOSE cur1;
END$$
DELIMITER ;

Here is SQLFiddle demo

peterm
  • 91,357
  • 15
  • 148
  • 157
  • @naveengoyal Did it help? Do you need more help with your question? If it was what you were looking for please, consider to **[accept](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)** the answer. – peterm Aug 16 '13 at 06:58