I have a simple stored procedure with comma separated input params. I will send Database Names in Json or Comma separated values.
Like DB1,DB2,DB3 etc..;
When ever I send that parameter will be loading that table in each of the Database.
I’m looking for loop condition and splitting values.
EXEC student_info (DBName = 'DB1,DB2,DB3,DB')
DELIMITER &&
ALTER PROCEDURE student_info (IN DBName varchar(100))
BEGIN
**Splitting comma separated**
**loop condition**
INSERT INTO @DBName.tbl_student(Name,Class)
SELECT Name,Class FROM DB.student_info ;
END &&
DELIMITER ;
What is the best way?
2
Answers
(Answer to the original question, before the edit)
Use
FIND_IN_SET
instead of a loopYou need to use prepared statements (see: PREPARE)
I tested with this:
After this the data checked to be copied from
student_info
to the differenttbl_student
tables.NOTE:
I would not create those tables, and copy the data, but I would use a view:
When you create a view, there is no need to copy the data to the other database, because this view will be updated automatically when records in the table
db.student_info
are updated/deleted or inserted.P.S. Above was testen on MySQL 8.x. Some functionality that is not available in earlier versions of MySQL (like
WITH
) is used.