I'm trying to write a MySQL stored procedure that accepts a SELECT
query and executes it against a list of databases. Is this even possible with MySQL?
Each customer in our application has their own database on the same instance. All customer databases are identical in their schema structure. Sometimes, I need to execute a simple SELECT query but across all the customer databases (e.g. SELECT COUNT(*) FROM users
).
I have stored procedures for the common recurring "instance-wide" queries like the user count but I don't want to create more of those for one-time queries (e.g. querying for corrupted records due to by buggy code, querying for columns that we are planning to deprecate, etc.).
My current solution is that I have a node
script that I run locally to generate SELECT queries for each database and then concatenate them all using UNION
to generate a giant query that I then execute on the database instance.
SELECT 'customerdb1' AS customer,
COUNT(*) AS user_count
FROM customerdb1.users
UNION
SELECT 'customerdb2' AS customer,
COUNT(*) AS user_count
FROM customerdb2.users
UNION
SELECT 'customerdb3' AS customer,
COUNT(*) AS user_count
FROM customerdb3.users