Home

Export resutts from an SQL to a csv text file directly

By selecting SQL (in lanuage dropdown), we write sqls and resultant data is displayed in Results tab below. Is there an sql statement that can directly export the results to a text file. In Sybase database administrator, we have equivalent statement as

SELECT * FROM EMPL ;
OUTPUT TO 'D:\\TEST\\sqlResults.txt' FORMAT TEXT;

Please suggest a solution.

Comments

  • I don't think these is a built in SQL Server function. Most examples show sqlcmd or powershell onelines.

    A LINQPad example using Util.WriteCsv() would look like:
    var query = @"SELECT * FROM EMPL";
    
    Connection.Open();
    
    using (var table = new DataTable())
    {
      using (var command = new SqlCommand(query, (SqlConnection)Connection))
      using (var reader = command.ExecuteReader())
      {
        table.Load(reader);
      }
      Util.WriteCsv(table, @"C:\Temp\empl.csv");
    }
  • Nescafe, your solution resolved my problem. Thank you.
Sign In or Register to comment.