Hello there.
I need to extract data from a MySQL DB table in CSV format.
My stored procedure below that works correctly in exporting the csv file, but the data sorting is wrong, because instead of sorting as in the query it inserts the column headers at the end of all the data instead of inserting the headers on the first row .
I also tried using the syntax
CASE WHEN
count_access = "count_access" THEN 0 ELSE CONVERT(
count_access, UNSIGNED) END DESC
without solving the problem.
sProc
CREATE DEFINER=`root`@`%` PROCEDURE `sProc`()
BEGIN
DECLARE start_date DATE;
DECLARE end_date DATE;
SET start_date = MAKEDATE( YEAR ( now()), 1 );
SET end_date = DATE_SUB(CURRENT_DATE, INTERVAL 8 DAY );
SET @`outfull` := CONCAT('C:/inetpub/ftproot/csv/', DATE_FORMAT(start_date,'%d_%m_%Y'), '-' , DATE_FORMAT(end_date,'%d_%m_%Y'), '_' , 'export.csv');
FLUSH HOSTS;
SET @`qry` := CONCAT('SELECT
\'Start_date\',
\'End_date\',
\'users\',
\'count_access\' UNION ALL
SELECT
`Start_date`,
`End_date`,
`users`,
IFNULL(`count_access`,0)
INTO OUTFILE \'', @`outfull`, '\'
FIELDS TERMINATED BY \'\;\' LINES TERMINATED BY \'\r\n\'
FROM `dotable`
ORDER BY CONVERT(`count_access`, UNSIGNED) DESC;');
PREPARE `stmt` FROM @`qry`;
SET @`qry` := NULL;
EXECUTE `stmt`;
DEALLOCATE PREPARE `stmt`;
END