Thursday, February 28, 2019

Create SQL procedure and insert data into table using while loop

Using this syntax procedures can be created. Variables are used in decision making statments
as while <condition>.


DELIMITER $$

DROP PROCEDURE IF EXISTS `procedure_insert_data`$$

CREATE PROCEDURE `procedure_insert_data`()
BEGIN
    DECLARE i INTEGER DEFAULT 0;
    DECLARE n INTEGER DEFAULT 0;
    DECLARE j INTEGER DEFAULT 0;
    DECLARE k INTEGER DEFAULT 0;
    SELECT COUNT(*) FROM abc INTO n;
    #loop starts
    WHILE i < n DO
      SET @siteId = 3;
        INSERT INTO abc (a,b,c)
        SELECT a,b,c
        FROM xyz LIMIT i,1;

          #nested loop start
          WHILE j < k DO

            INSERT INTO abd (a, b, c)
            SELECT a, b, c FROM wxy
            WHERE   LIMIT j,1;

            SET j = j + 1;
          END WHILE;
          SET j = 0;
      SET i = i + 1;
    END WHILE;
END$$

DELIMITER ;

A way to call the procedure.
CALL procedure_insert_data();