6

I want to use the loop index "i" in the result of my select statement in order to insert it into another table. Is is like:

set i=0;
while i<25 do

    insert into a (x,y,z)
    select a,b,i
    from table1;

    set i= i+1;
end while;

What is the way to do it?

1
  • Do you want to insert all rows of table1 ? is there some where condition ? maybe you can post a real sample. Commented May 13, 2014 at 17:09

2 Answers 2

2

DOne :)

I have just created variable i as @i and it is all solved.

Like this:

set @i=0;
while @i<25 do

    insert into a (x,y,z)
    select a,b,@i
    from table1;

    set @i= @i+1;
end while;

thx anyway :)

Sign up to request clarification or add additional context in comments.

3 Comments

FYI, this will be incredibly slow. You should use a set-based approach.
Any samples that I can use?
Yes, create a numbers table then join to it.
0

Open the table separately asa cursor, put fields in to variables, then use those variables and i to insert data in to the table with a

insert into a (x,y,z) values (var1, var2, i).

What you have written would put multiple rows in to a table a with each value of i.

1 Comment

Would u please explain a little bit more? I am new in mysql and did not understand this answer...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.