Query SQL server from command line

Ever need to query SQL database from command line to export the result to a CSV file? I have used “sqlcmd” to do the job. The following is an example for that:

sqlcmd -S [server name] -d [database name] -i [SQL file name] -o [CSV file name] -s”,” -w 300

The command explains

  • There are a lot of options in sqlcmd, enter “sqlcmd -?” from the command line to see the full list of options;
  • [server name] is the name of the server where the database is located;
  • [database name] is the database which you want to query;
  • [SQL file name] is a plain text file containing the SQL queries, normally ended with the extension “.sql”, e.g. create table… select * from table…;
  • [CSV file name] is the output CSV file name, which normally has the extension “.csv”;
  • -s”,”, is where you specify the delimiter, comma in this case, other characters can be used;
  • -w 300, is the fixed width of output record, 300 characters in this case;

Spread the word. Share this post!

Leave A Reply

Your email address will not be published. Required fields are marked *