Search
Database

SQL Server 2008: The sqlcmd Command-Line Utility

First published Rewritten 1 min readBy Programming4us Editorial Team

sqlcmd is the command-line query tool that replaced osql and isql in SQL Server 2005 and 2008. It is ideal for running scripts in batch files, scheduled tasks and installations, and for emergency access when Management Studio won't connect.

Connecting

sqlcmd -S SERVER\INSTANCE -E
sqlcmd -S SERVER -U sa -P MyPassword
  • -S server and instance,
  • -E Windows authentication (trusted connection),
  • -U and -P SQL Server login and password,
  • -d database to use.

In interactive mode type T-SQL and finish each batch with GO. Type EXIT or QUIT to leave.

Running a query or a script

sqlcmd -S SQL01 -E -Q "SELECT name FROM sys.databases"
sqlcmd -S SQL01 -E -i C:\Scripts\maintenance.sql -o C:\Logs\maintenance.log
  • -q runs a query and stays open; -Q runs it and exits,
  • -i input script file (several can be listed),
  • -o output file.

Useful formatting options

  • -W removes trailing spaces,
  • -s "," sets the column separator (with -W this gives simple CSV output),
  • -h -1 removes column headers,
  • -b returns an error level when a script fails, so batch files can check %ERRORLEVEL%.

Scripting variables

Use $(name) in a script and pass values with -v:

-- backup.sql
BACKUP DATABASE [$(db)] TO DISK = '$(path)\$(db).bak';
sqlcmd -S SQL01 -E -i backup.sql -v db="Sales" path="E:\Backup"

Inside scripts, :setvar defines variables and :r file.sql includes another file. These commands also work in Management Studio when SQLCMD Mode is enabled from the Query menu.

The dedicated administrator connection (DAC)

When the server is unresponsive, connect with -A:

sqlcmd -S SQL01 -E -A

The DAC uses reserved resources so a sysadmin can diagnose blocking or kill runaway sessions. Only one DAC connection is allowed at a time; remote DAC must be enabled with sp_configure 'remote admin connections', 1.

Today's equivalent

sqlcmd still ships with SQL Server, and a newer cross-platform go-sqlcmd adds features such as creating SQL Server containers. Azure Data Studio's successor tools and VS Code with the MSSQL extension cover interactive work.