0

I have some schemas, all with the same format. The format is: schema name, underscore, single digit (example: database_1). How can I loop through all of these schemas easily? I tried SET @num = 1; USE database_@num; But it says

Unknown database 'database_@num'

I'm using MariaDB 10.1.30

asked Jun 30, 2018 at 4:51
3
  • Having a bunch of 'identical' databases (or tables) is usually a bad way to design the schema. Rather than finding a solution to database_@num, let's discuss getting rid of the problem. Commented Jul 1, 2018 at 20:59
  • Can you suggest a good place to discuss such issues? Commented Jul 1, 2018 at 23:08
  • Start a new question. Explain the purpose of having database_nnn. Tell us what kind of data (shopping, scientific, time series, etc) that you have. Ask for performance advice on fetching from different databases due to the split you decided on. Commented Jul 2, 2018 at 1:38

1 Answer 1

1

The particular statement you want to run - USE - is not supported by dynamic SQL. I therefore suspect what you want to do is not currently possible.

If dynamic SQL did support the USE statement, you could have done:

MariaDB 10.1:

SET @sql = CONCAT('USE database_', @num);
PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt;` 

MariaDB 10.3:

EXECUTE IMMEDIATE CONCAT('USE database_', @num); 

Both result in:

ERROR 1295 (HY000): This command is not supported in the prepared statement protocol yet

The MariaDB knowledge base has a list of permitted statements that you can PREPARE. Effectively, this is a list of statements that can be used in dynamic SQL.

EDIT:

So instead I suppose you're left with options such as:

  1. Generate your statements as text -- un-roll your loop to a long list of statements, dump them to a .sql file and then SOURCE that file.
  2. Use a scripting language such as Python, bash, PHP etcetera. Do the loop in the scripting language. (Do not use prepared statements for the USE statement, obviously.)
answered Jun 30, 2018 at 22:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.