Search code examples
mysqlloopsaltersequential

Add columns to mySQL table with loops


I'm fairly new to mySQL. Let's say I'm adding columns to my table like so:

ALTER TABLE table ADD client_input_2.0_1 LONGTEXT;

And I would like to add a number of similar sequential columns, i.e.

ALTER TABLE table ADD client_input_2.0_2 LONGTEXT;
ALTER TABLE table ADD client_input_2.0_3 LONGTEXT;
ALTER TABLE table ADD client_input_2.0_4 LONGTEXT;

etc. all the way up to a large enough number that this will take quite some time if I do this manually. In my case, 2.0 represents a section/part, and the last number represents a question number, which could be anywhere from 1-50 or so depending on the section, so manually creating this table would take a lot of time.

Is there a way for me to do this in a script using some sort of loop, incrementing the col# each time?

Much appreciated,


Solution

  • Edited code

    try using a stored procedure

    DELIMITER $$
    DROP PROCEDURE IF EXISTS RepeatLoopProc$$
    CREATE PROCEDURE RepeatLoopProc()
      BEGIN
              DECLARE x  INT;
              DECLARE str  VARCHAR(255);
              Declare @sql nvarchar(4000);
              SET x = 0;
    
              REPEAT
                          SET str =  '';
                          SET  str = CONCAT(str,'client_input_2.0_',x);
                          SET  x = x + 1;
                          set @sql='ALTER TABLE table_name ADD '+ str +' column-definition';
                          exec sp_executesql @sql;
              UNTIL x  > 50
              END REPEAT;
    
      END$$
    DELIMITER ;
    

    Hope this will help you.