简体   繁体   English

将带有列名的 sql 表数据导出到 csv 文件

[英]export sql table data with column names to csv file

I am trying to export the data from sql server tables to a csv file without ssms.我正在尝试将数据从 sql server 表导出到没有 ssms 的 csv 文件。

i am trying to achieve it by creating a stored procedure using bcp.我试图通过使用 bcp 创建一个存储过程来实现它。

declare @sql nvarchar(4000); select @sql = 'bcp "select * from table" queryout c:\file.csv -c -t, -T -S'+ @@servername exec xp_cmdshell @sql

1 ) This query produces the expected results. 1 ) 此查询产生预期结果。 But what i want is it should also include the column names in the csv files.但我想要的是它还应该包含 csv 文件中的列名。 So how can i achieve that ?那么我该如何实现呢?

2) I want this result for all the tables in the given database. 2)我想要给定数据库中所有表的这个结果。 So how to do that ?那么该怎么做呢?

Please give some suggestions or solution as soon as possible请尽快给出一些建议或解决方案

thanks谢谢

Only workarounds I know of...只有我知道的解决方法...

  1. Query the data dictionary and produce a csv field list, then concatenate the header.csv with the data.csv.查询数据字典并生成一个 csv 字段列表,然后将 header.csv 与 data.csv 连接起来。 This would be querying the columns table, but you would need to take care to generate the SQL to match since you want to remove any and all chances that the column list doesn't match the data.这将查询列表,但您需要注意生成要匹配的 SQL,因为您要删除列列表与数据不匹配的所有可能性。

  2. Create a view with the first row having all field names union all with a select on the data.创建一个视图,第一行的所有字段名称union all与数据的选择结合在一起。

Something like:就像是:

SELECT 'a', 'b', 'c' UNION ALL SELECT a, b, c FROM table

This may require type conversions for dates, though.不过,这可能需要对日期进行类型转换。

I would suggest doing something along the lines of:我建议按照以下方式做一些事情:

@echo off
bcp "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<table_name>' AND TABLE_SCHEMA='<table_schema>'" queryout c:\file.csv -c -r, -T -S <server_name> -d <database_name>
bcp "select * from <table_schema>.<table_name>" queryout c:\data.csv -c -t, -T -S <server_name> -d <database_name>
echo. >> c:\file.csv
type c:\data.csv >> c:\file.csv
del c:\data.csv

in a .bat file..bat文件中。

I think that for what you want to do, it's better to just use the bcp command from a batch file/command line, instead of enabling the xp_cmdshell in SQL Server which could introduce a security issue.我认为对于您想要做的事情,最好只使用批处理文件/命令行中的bcp命令,而不是在 SQL Server 中启用xp_cmdshell ,这可能会引入安全问题。

Additionally, I'd like to point out that I'm not sure if the columns will always come out in the same order (in my case it did).此外,我想指出,我不确定列是否总是以相同的顺序出现(在我的情况下确实如此)。

EDIT: Batch file explanation.编辑:批处理文件说明。 I basically ran 2 bcp commands and sent the output to 2 different files, as I couldn't find an option to append the output to another file.我基本上运行了 2 个bcp命令并将输出发送到 2 个不同的文件,因为我找不到将输出附加到另一个文件的选项。 I then merely used the type command to add the data to the file already containing the column list, and deleted the file with the data as it is no longer needed.然后我只使用type命令将数据添加到已经包含列列表的文件中,并删除了不再需要数据的文件。

Feel free to modify and mess around with it and let me know if you run into any problems.随意修改和弄乱它,如果遇到任何问题,请告诉我。

Try this code if you want column name with SQL table data :-如果您想要带有 SQL 表数据的列名,请尝试此代码:-

 public void ExportExcelFileToFolder()
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM MachineMaster"))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);
                        using (XLWorkbook wb = new XLWorkbook())
                        {
                            wb.Worksheets.Add(dt, "SheetName");

                            HttpContext.Current.Response.Clear();
                            HttpContext.Current.Response.Buffer = true;
                            HttpContext.Current.Response.Charset = "";
                            HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                            HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=SqlExport.xlsx");
                            using (MemoryStream MyMemoryStream = new MemoryStream())
                            {
                                wb.SaveAs(MyMemoryStream);

                                string fileName = Guid.NewGuid() + ".xlsx";
                                string filePath = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/ExeclFiles"), fileName);


                                MyMemoryStream.WriteTo(new FileStream(filePath, FileMode.Create));
                                HttpContext.Current.Response.Flush();
                                HttpContext.Current.Response.End();
                            }
                        }
                    }
                }
            }
        }
    }
  • Install-Package ClosedXML -Version 0.92.1安装包 ClosedXML -版本 0.92.1

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

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