我想用mySQL标头动态导出CSV文件。我尝试了shadow0359的答案: MySQL: Dynamically export CSV file with headers ,但我相信他的解决方案是将标题导出到记录的底部而不是顶部。有谁知道如何从mySQL动态导出CSV文件(顶部带有标题)?
我的代码(要创建的脚本):
存储过程
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `p_test`(in_Accountid
varchar(30))
BEGIN
SET @default_group_concat_max_len = (SELECT @@group_concat_max_len);
SET SESSION group_concat_max_len = 1000000;
SET @FilePath:='C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/';
SET @FileName:=CONCAT(in_AccountID,'_',DATE_FORMAT(NOW(),'%Y-%m-
%d'),'.xls');
SET @FullFilePath:=CONCAT(@FilePath,@FileName);
SET @TableName:='temp_transactionslines';
SET @TableSchema:='melhor_metade_2016';
SET @SQL = ( select CONCAT('SELECT
TransactionID
,RecordID
,AccountID
,AccountDescription
,SourceDocumentID
,SystemEntryDate
,Description
,DebitAmount
,CreditAmount
,Period
,TransactionDate
,CustomerTaxID
,CustomerID
INTO OUTFILE \''
, @FullFilePath, '\'
FROM (SELECT '
,group_concat(CONCAT("'", COLUMN_NAME,"'"))
,' UNION ALL SELECT * FROM
temp_transactionslines order by TransactionID ASC) as tmp')
from INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
AND TABLE_SCHEMA = @TableSchema
order BY ORDINAL_POSITION );
SET SESSION group_concat_max_len = @default_group_concat_max_len;
PREPARE dynamic_statement FROM @SQL;
EXECUTE dynamic_statement;
DEALLOCATE PREPARE dynamic_statement;
END$$
DELIMITER ;
表格
CREATE TABLE `temp_transactionslines` (
`TransactionID` varchar(70) NOT NULL,
`RecordID` varchar(30) NOT NULL,
`AccountID` varchar(30) DEFAULT NULL,
`AccountDescription` varchar(100) DEFAULT NULL,
`SourceDocumentID` varchar(60) DEFAULT NULL,
`SystemEntryDate` varchar(19) DEFAULT NULL,
`Description` varchar(200) DEFAULT NULL,
`DebitAmount` float(13,2) DEFAULT NULL,
`CreditAmount` float(13,2) DEFAULT NULL,
`Period` int(2) DEFAULT NULL,
`TransactionDate` varchar(19) DEFAULT NULL,
`CustomerTaxID` varchar(20) DEFAULT NULL,
`CustomerID` varchar(30) DEFAULT NULL,
`SupplierID` varchar(30) DEFAULT NULL,
KEY `i_accountID` (`AccountID`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;
数据
INSERT INTO `melhor_metade_2016`.`temp_transactionslines`
(`TransactionID`,
`RecordID`,
`AccountID`,
`AccountDescription`,
`SourceDocumentID`,
`SystemEntryDate`,
`Description`,
`DebitAmount`,
`CreditAmount`,
`Period`,
`TransactionDate`,
`CustomerTaxID`,
`CustomerID`,
`SupplierID`)
VALUES
('a','b',3,4,5,2, 1, 1,null,3,1,2,3,4);
答案 0 :(得分:1)
您生成以下查询:
SELECT 'TransactionID'
,'RecordID'
,'AccountID'
-- more column names
UNION ALL
SELECT * FROM temp_transactionslines
order by TransactionID ASC
ORDER BY子句适用于完整的UNION集。如果只想对第二个查询结果进行排序,则应将查询用括号括起来:
SELECT 'TransactionID'
,'RecordID'
,'AccountID'
-- more column names
UNION ALL
(SELECT * FROM temp_transactionslines order by TransactionID ASC)