使用INTO OUTFILE的mysql存储过程

时间:2014-03-08 05:30:11

标签: mysql stored-procedures

我有一个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

2 个答案:

答案 0 :(得分:3)

假设(为了示例)您的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'已存在

解决此问题的一种方法是在过程本身内向文件名附加时间戳,或者通过参数传递值。

答案 1 :(得分:0)

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();

这对你有用吗?