Execute the result of a sql select in MySql

元气小坏坏 提交于 2021-01-27 21:30:40

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/16012630/execute-the-result-of-a-sql-select-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!