mysql outfile 变量,我可以使用变量在mysql中指定OUTFILE吗

Is there a way to do something like the following ? which doesn't work but shows what I want to do

SET @OutputPath = '/Users/jo/Documents'

SET @fullOutputPath = CONCAT(@OutputPath,'/','filename.csv')

SET @fullOutputPath2 = CONCAT(@OutputPath,'/','filename2.csv')

SELECT * INTO OUTFILE @fullOutputPath

FIELDS TERMINATED BY ','

OPTIONALLY ENCLOSED BY '"'

FROM database.tableName;

SELECT * INTO OUTFILE @fullOutputPath2

FIELDS TERMINATED BY ','

OPTIONALLY ENCLOSED BY '"'

FROM database.tableName2;

解决方案

Edit: Saving data(e.g. a table) into file without using variable (only constant values)

-- folder_path could could be like => c:/users/sami

-- choose the directory/folder already available in system

-- and make sure you have access to write the file there

SELECT * INTO OUTFILE 'folder_path/filename.csv'

FIELDS TERMINATED BY ','

OPTIONALLY ENCLOSED BY '"'

FROM database.tableName;

Now using variable

Whenever you have to use a variable name in sql, you need dynamic sql (which is applicable in stored procedures only, neither in simple sql query nor in triggers or functions)

SET @OutputPath := 'Users/jo/Documents'; //or any folder_path

SET @fullOutputPath := CONCAT(@OutputPath,'/','filename.csv');

SET @fullOutputPath2 := CONCAT(@OutputPath,'/','filename2.csv');

set @q1 := concat("SELECT * INTO OUTFILE ",@fullOutputPath,

" FIELDS TERMINATED BY ','

OPTIONALLY ENCLOSED BY '\"'

FROM database.tableName");

set @q2 := concat("SELECT * INTO OUTFILE ",@fullOutputPath2,

" FIELDS TERMINATED BY ','

OPTIONALLY ENCLOSED BY '\"'

FROM database.tableName2");

prepare s1 from @q1;

execute s1;deallocate prepare s1;

prepare s1 from @q2;

execute s1;deallocate prepare s1;

As you had both ' and " in your query already, so I concatenated your query using " and used \ to escape your original " to ensure its use as a literal character and not used for concatenation

I just told the use of variable in sql. First You should make sure if your query works like example at the top (without using variable)

Conclusion: If your above query works fine then my told dynamic sql will work as well given that you are using it in some stored procedure.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值