Reputation: 8722
I am trying to get MySql to execute the result of the below statement as further sql statements. I believe in oracle sqlplus this is achieved using the spool
function. How is this achieved in Mysql?
select concat('OPTIMIZE TABLE `', ist.TABLE_SCHEMA,'`.', ist.TABLE_NAME, ';') FROM INFORMATION_SCHEMA.TABLES ist where table_schema = 'my_schema';
Upvotes: 3
Views: 13655
Reputation: 51878
You have to use prepared statements.
SET @s:='';
SELECT @s:=concat(@s, 'OPTIMIZE TABLE `', ist.TABLE_SCHEMA,'`.', ist.TABLE_NAME, ';') FROM INFORMATION_SCHEMA.TABLES ist where table_schema = 'my_schema';
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
But you have to put all the optimize table statements into one variable, that's why I'm concatenating @s
with itself. Else you'd have to work with a cursor, which is unnecessary work.
As of MySQL 5.0.23, the following additional statements are supported:
ANALYZE TABLE
OPTIMIZE TABLE
REPAIR TABLE
EDIT: An even simpler approach is this:
SELECT CONCAT('OPTIMIZE TABLE `', ist.TABLE_SCHEMA,'`.', ist.TABLE_NAME, ';') FROM INFORMATION_SCHEMA.TABLES ist WHERE table_schema = 'my_schema'
INTO OUTFILE '/tmp/my_optimization';
SOURCE 'tmp/my_optimization';
Upvotes: 6
Reputation: 350
If you are accessing it via the mysql command line client you could just pipe the output of the first command into the cli tool again.
mysql --batch --silent -nBe "select concat('OPTIMIZE TABLE `', ist.TABLE_SCHEMA,'`.', ist.TABLE_NAME, ';') FROM INFORMATION_SCHEMA.TABLES ist where table_schema = 'my_schema'" | mysql my_schema
Upvotes: 1