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';