MS SQL - Command line cheatsheet

By xngo on October 7, 2019

Execute SQL statements

sqlcmd -S MyServer\Name -d myDB -E -Q "SELECT COUNT(*) FROM SYSOBJECTS"
-- sqlcmd -S localhost -d master -E -e -Q "SELECT COUNT(*) FROM SYSOBJECTS"
-- sqlcmd -S . -d master -E -e -Q "SELECT COUNT(*) FROM SYSOBJECTS"
sqlcmd -S MyServer\Name -d myDB -E 
    -i "C:\Some Folder\file.sql" -i \\<Server>\<Share$>\file2.sql 
  • -E: Uses a trusted connection(i.e Windows Authentication) instead of using a user name and password to sign in to SQL Server.
  • -Q: Executes the query string when sqlcmd starts and then immediately exits sqlcmd. Multiple-semicolon-delimited queries can be executed.

Export to CSV

sqlcmd -S MyServer\Name -d myDB -E -Q "SELECT col1, col2, col3 FROM tableName" 
       -h-1 -s"," -W -o "MyData.csv" 
  • -h-1: Remove column name headers from the results.
  • -s",": Set column separator to use comma.
  • -W: Remove trailing spaces from each individual field.

About the author

Xuan Ngo is the founder of He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.