从 SQL 导出时,列名未保存在文本文件中

Column names are not saving in text file while exporting from SQL

我正在从文本文件中的 SQL 导出 table,数据导出正常,但列名未出现在文本文件中。 这是代码:

   public static void getfiles()
   {
       SqlDataReader reader;
       string query = "Select * from tTable";
       string connStr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
       string strDelimiter = "\"|\"";
       string strFilePath = @"path";
       StringBuilder sb = new StringBuilder();

       using (SqlConnection conn = new SqlConnection(connStr))
       {
           conn.Open();
           using (reader = new SqlCommand(query, conn).ExecuteReader())
           {
               if (reader.HasRows)
               { 
                   Object[] items = new Object[reader.FieldCount];

                   while (reader.Read())
                   {
                       reader.GetValues(items);
                       foreach (var item in items)
                       {

                           sb.Append(item.ToString());
                           sb.Append(strDelimiter);
                       }
                       sb.Append("\n");
                   }
               }
           }
           conn.Close();
           File.WriteAllText(strFilePath, sb.ToString());
       }
   }

不知道这个方法有什么变化

您根本不写列名。这可以通过 reader.GetName() 方法实现,如下所示:

using (reader = new SqlCommand(query, conn).ExecuteReader())
{
    for (int i=0; i<reader.FieldCount; i++)
    {
        sb.Append(reader.GetName(i));
        sb.Append(strDelimiter);
    }
    sb.Append(Environment.NewLine);

    // your code here...
    if (reader.HasRows)
    {
        // etc...
    }
}

您可以在 select 语句中包含列名....

Select Column1 from(select Sorter = 1, Convert(VARCHAR(max), Column1) as Column1
    from TableName union all
    select 0, 'Column1') X
order by Sorter, Column1