简体   繁体   中英

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.

I am using asp.net with C# as front end.

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.

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.

Use LinqToCSV and write the file to the server. Writing should be straight forward using the built in methods of 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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