Search code examples
c#sqlsql-serversaveqsqlquery

How to retrieve column names when saving a SQL query to a text file


I wrote a method which saves the content of a specific table to a text file. Unfortunately the names of the columns are not retrieved. "Only" the data of each cell is written to the text file.

How do i need to adapt my code to also include the name of the columns?

private void WriteSQLQueryOutputToTextFile(string DBUser, string DBUserPassword, string sqlQuery, string databaseName, string nameOfOutputFile, string nameOfRow0, string nameOfRow1, string nameOfRow2)
{
  StreamWriter outputFile = new StreamWriter(dWTestResult + "\\DatabaseUpgradeCheck\\" + nameOfOutputFile);

  using (SqlConnection sqlCon = new SqlConnection("Data Source=" + GetEnvironmentVariable.MachineName + "; Initial Catalog=" + databaseName + "; User ID=" + DBUser + "; Password=" + DBUserPassword + ";"))
  {
      SqlCommand command = new SqlCommand(sqlQuery, sqlCon);
      sqlCon.Open();
      SqlDataReader reader = command.ExecuteReader();
      try
      {
          while (reader.Read())
          {
              outputFile.WriteLine(String.Format("{0}, {1}, {2}",
              reader[nameOfRow0], reader[nameOfRow1], reader[nameOfRow2]));
          }
      }
      catch (Exception ex)
      {
          logger.Debug(ex, "Writing Database Output to the text file failed");
      }
      finally
      {
          reader.Close();
          outputFile.Close();
      }     
   }
}

Solution

  • Add a count variable, and if count == 0 add the column names. It looks like you know the names of the columns already so you have a couple of options.

    First option: Just write the name.

    try
    {
        int count = 0;
        while (reader.Read())
        {
            if (count == 0)
            {
                outputFile.WriteLine(String.Format("{0}, {1}, {2}",
                    nameOfRow0, nameOfRow1, nameOfRow2));
            }
    
            outputFile.WriteLine(String.Format("{0}, {1}, {2}",
                reader[nameOfRow0], reader[nameOfRow1], reader[nameOfRow2]));
    
            count++;    
        }
    }
    

    Or (if you don't know the column names) use reader.GetName(i):

    try
    {
        int count = 0;
        while (reader.Read())
        {
            // if this is the first row, read the column names
            if (count == 0)
            {
                outputFile.WriteLine(String.Format("{0}, {1}, {2}",
                   reader.GetName(0), reader.GetName(1), reader.GetName(2)));
            }
    
            // otherwise just the data (including 1st row)
            outputFile.WriteLine(String.Format("{0}, {1}, {2}",
               reader.GetValue(0), reader.GetValue(1), reader.GetValue(2)));
    
            count++;         
        }
    }