How to improve performance merging multiple table via cursor
Don't use a cursor, use a JOIN to do the entire set of statements all at once.
Here are two examples:
http://mysql.rjweb.org/doc.php/myisam2innodb#generating_alters
http://mysql.rjweb.org/doc.php/limits#767_limit_in_innodb_indexes
Both of them depend on doing lots of statements, then you manually copy the commands into MySQL commandline tool (or some other tool).  They could be adapted to do prepare/execute.
See also the following for construction a single query to pivot a table:
http://mysql.rjweb.org/doc.php/pivot