简体   繁体   English

将查询结果另存为csv文件在特定文件夹下的服务器上

[英]Save Query Result as csv file on server under specific folder

I want to save sql server 2008 query result to server itself and store file link in another table so whenever i want i can download the file, without re executing the query. 我想将sql server 2008的查询结果保存到服务器本身,并将文件链接存储在另一个表中,以便每当我希望可以下载文件时,而无需重新执行查询。

I am using asp.net with C# as front end. 我使用C#作为前端的asp.net。

in front end it is like. 在前端就像。 Enter Area Code
user enters area code and click on submit, it will search all record with the same area code in database and save it in csv file on server. 用户输入区号并单击提交,它将在数据库中搜索具有相同区号的所有记录并将其保存在服务器上的csv文件中。

i am using following code. 我正在使用以下代码。

select * from mytablename where area_code=21

save this result on my server. 将此结果保存在我的服务器上。

            FileStream fs = new FileStream(path, FileMode.CreateNew);
            StreamWriter CsvfileWriter = new StreamWriter(fs);
            //This Block of code for getting the Table Headers

            for (int i = 0; i < dr.FieldCount; i++)
            {
                tableColumns.Columns.Add(dr.GetName(i));
            }
            CsvfileWriter.WriteLine(tableColumns.Columns.ConcatUsing(","));

            StringBuilder sb = new StringBuilder();
            while (dr.Read())
            {
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    sb.AppendFormat("{0},", dr[i]);
                }
                sb.AppendLine();
            }
            CsvfileWriter.WriteLine(sb.ToString());

Save the path name is table. 保存的路径名是table。

Use LinqToCSV and write the file to the server. 使用LinqToCSV并将文件写入服务器。 Writing should be straight forward using the built in methods of LinqToCSV. 使用LinqToCSV的内置方法可以直接进行编写。 Then store the file name in the table. 然后将文件名存储在表中。

declare @sql varchar(8000)
select @sql = 'bcp "select * from mytablename where area_code=21" queryout c:\bcp\[filename] -c -t, -T -S' + @@servername
exec master..xp_cmdshell @sql

execute this query you have to set path for write file. 执行此查询,您必须设置写入文件的路径。 currently in this query you have to create a "bcp" folder in "C:\\ "Drive . 当前在此查询中,您必须在“ C:\\” Drive中创建一个“ bcp”文件夹。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM