1

I have a TableA from where I would like some information for e.g. tableA has columns **name, age and rollNo** and I would like to insert **age** and **rollNo** from tableA to tableB wherever the age is greater than 20 and rollNo less than 500

Is there anyway this can be done in MySQL using a procedure or something.

4
  • "Insert records in a loop" is always a bad idea. This can be done in a single statement. Commented Sep 17, 2015 at 21:13
  • @Cᴏʀʏ sometimes it is unavoidable. In such cases, a stored procedure making use of CURSORs is the only way to go if it must be done on the server. Commented Sep 17, 2015 at 21:26
  • @Uueerdo: I guess I don't know how powerful MySQL's query syntax is -- I have never used a CURSOR in T-SQL, for example (instead, WHILE loops are fantastic). You can almost always write a loop without a CURSOR, even if CURSOR is the easy way out. Stuff like that should be a last resort (in my humble opinion, of course). Commented Sep 17, 2015 at 22:04
  • @Cᴏʀʏ You still need to loop through cursor results in MySQL stored procs. It's not an instead thing; just what you use to be able to iterate through results within a stored procedure. Commented Sep 17, 2015 at 22:31

1 Answer 1

2

This can be done in a single query using the INSERT ... SELECT syntax:

INSERT INTO TableB (Age, RollNo)
SELECT Age, RollNo
FROM TableA
WHERE Age > 20 AND RollNo < 500
Sign up to request clarification or add additional context in comments.

1 Comment

@Cory I had to make a few modifications but worked like a charm. Thanks a lot.

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.