[英]mysql stored procedure with INTO OUTFILE
我有一个mysql存储过程,我想做两件事1.查询表并将结果作为普通结果集返回。 2.遍历结果集并从过程本身创建格式化的文本文件。
我查看了INTO OUTFILE,但似乎INTO OUTFILE将结果raw写入指定文件,如果我们使用INTO OUTFILE,则结果集将为空。 似乎我们不能兼得。
这是我的样本SP
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `getdeals`()
BEGIN
select * INTO OUTFILE '/Users/tuser/sql/out.txt' from deals;
END
有什么想法吗 ? 谢谢Prem
假设( 为了示例 )您的deals
表看起来像
--------------------------- | id | deal_date | deal | --------------------------- | 1 | 2014-03-10 | Deal1 | | 2 | 2014-03-11 | Deal2 | | 3 | 2014-03-12 | Deal3 | ---------------------------
现在你的程序代码看起来像
DELIMITER //
CREATE PROCEDURE get_deals()
BEGIN
-- create a temporary table and fill it with the desired subset of data
-- Apply WHERE and ORDER BY as needed
DROP TEMPORARY TABLE IF EXISTS tmp_deals;
CREATE TEMPORARY TABLE tmp_deals
SELECT id, deal_date, deal -- explicitly specify real column names here. Don't use SELECT *. It's a bad practice.
FROM deals
ORDER BY id DESC;
-- write the resultset to the file
SELECT *
INTO OUTFILE '/path/to/deals.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM tmp_deals;
-- return the resultset to the client
SELECT * FROM tmp_deals;
END//
DELIMITER ;
执行后:
CALL get_deals();
在客户端,你会得到:
--------------------------- | id | deal_date | deal | --------------------------- | 3 | 2014-03-12 | Deal3 | | 2 | 2014-03-11 | Deal2 | | 1 | 2014-03-10 | Deal1 | ---------------------------
文件内容如下:
3,"2014-03-12","Deal3" 2,"2014-03-11","Deal2" 1,"2014-03-10","Deal1"
注意:使用OUTFILE
MySQL时需要重新创建文件。 如果将文件保留在输出目录中,则在后续过程调用中,您将收到以下错误
文件'/path/to/deals.txt'已存在
解决此问题的一种方法是在过程本身内向文件名附加时间戳,或者通过参数传递值。
DELIMITER $$
SqlCeConnection connection = new SqlCeConnection(conSTR);
string sql = "SELECT * INTO OUTFILE '/Users/tuser/sql/out.txt' FROM deals";
connection.Open();
SqlCeCommand cmd = new SqlCeCommand(sql, connection);
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
DataSet ds=new DataSet();
da.Fill(ds);
//datagridview1 is name of datagridview in form:
datagridview1.DataSource=ds.Tables[0];
connection.Close();
这对你有用吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.