An example of dynamic SQL is fixing a faulty schema and using it more conveniently.
For example, if you have hundreds of users and someone initially decided to create a new table for each user, you might want to redo the database to have only one table. Then you will need to transfer all existing data to this new system.
You can query the information schema for table names with a specific name pattern or contain specific columns, then use dynamic SQL to select all the data from each of these tables, and then put them in one table.
INSERT INTO users (name, col1, col2) SELECT 'foo', col1, col2 FROM user_foo UNION ALL SELECT 'bar', col1, col2 FROM user_bar UNION ALL ...
Then, hopefully, after that you won't need to access dynamic SQL again.
source share