Export a query result to a file

from the Artful MySQL Tips List

SELECT ... INTO OUTFILE | DUMPFILE ... exports a query result to a file on the server, but it demands a literal filename. What if you need a generic method that accepts the query and filename as variables? PREPARE the command, eg to save the content of a text column in one row of murphy(id INT PRIMARY KEY, law TEXT) ...SET @id=100;
SET @f = 'saying.txt';
SET @sql = CONCAT( 'SELECT law FROM murphy WHERE id=',@id,
' INTO DUMPFILE',' ',CHAR(39),@f,CHAR(39) );
PREPARE stmt FROM @sql;
EXECUTE stmt;
DROP PREPARE stmt;