Ask the Expert

How do I convert a SQL server database table into a text file and vice versa?

How do I convert a SQL server database table into a text file and vice versa? I know that BCP Utilities is there. Can you please give me some code?
It depends on the format of the text file ;)

To get an XML text file, simply load the dataset with the query (using a SqlDataAdapter probably) and use the following code:

DataSet ds;
//Load data from SQL
ds.WriteXml(@"c:\data.xml");

For a comma-separated text file, you will need to iterate the rows and dump them:

DataSet ds = new DataSet();
//Load data from SQL

using (StreamWriter sw = new StreamWriter(@"c:data.csv"))
{
 //First line contains column names
 foreach (DataColumn col in ds.Tables["titles"].Columns)
 {
  sw.Write(col.ColumnName);
  sw.Write(";");
 }
 sw.WriteLine();
 //Iterate rows
 foreach (DataRow row in ds.Tables["titles"].Rows)
 {
  //Dump each column value for the current row
  foreach (DataColumn col in ds.Tables["titles"].Columns)
  {
   sw.Write(row[col]);
   sw.Write(";");
  }
  sw.WriteLine();
 }
}

This was first published in October 2003

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: