SQL Server 2008: The sqlcmd Command-Line Utility
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
-Sserver and instance,-EWindows authentication (trusted connection),-Uand-PSQL Server login and password,-ddatabase 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
-qruns a query and stays open;-Qruns it and exits,-iinput script file (several can be listed),-ooutput file.
Useful formatting options
-Wremoves trailing spaces,-s ","sets the column separator (with-Wthis gives simple CSV output),-h -1removes column headers,-breturns 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.