Keyboard and terminal window, representing the sqlcmd command-line tool for SQL Server

sqlcmd: Running Scripts, Automating Tasks and Practical Tips for SQL Server’s Command-Line Tool

How to use sqlcmd for SQL Server automation: the two versions, key parameters such as -b and -v, scripting variables, :r and :connect, certificate errors and secure credential handling.

March 31, 2023

SSMS covers most day-to-day work, but when you need to run the same script on ten servers, schedule a maintenance task, automate a deployment step or get in while the server isn’t responding, the command line comes to the front. sqlcmd is Microsoft’s command-line tool for SQL Server: it runs T-SQL commands and script files, writes results to files, can be parameterized with variables and returns an exit code on errors.

This guide covers basic sqlcmd usage, the parameters that matter most for automation, scripting variables, the encryption default that comes with newer drivers, and what to watch for to use it securely.

SQL Server Automation

Want to automate routine DBA work?

Aryasoft turns maintenance, deployment and reporting tasks into repeatable scripts and observable jobs.

Get Support

The Two Versions of sqlcmd

There are two sqlcmd tools today:

  • sqlcmd (ODBC): the classic version that comes with SQL Server setup and the Microsoft Command Line Utilities package. It uses the ODBC driver.
  • sqlcmd (Go): a newer version that runs on Windows, Linux and macOS as a single executable. It supports most of the classic parameters, and adds extra commands such as creating containers for local development.

The output of sqlcmd -? tells you which one you’re using. The examples in this article work with both.

Basic Connection and Query

# Run one query with Windows authentication and exit
sqlcmd -S SERVER -E -Q "SELECT @@SERVERNAME, @@VERSION"

# Named instance and a specific database
sqlcmd -S SERVER\InstanceName -E -d SalesDB -Q "SELECT COUNT(*) FROM dbo.Orders"

# Interactive session (type commands and run them with GO)
sqlcmd -S SERVER -E

-Q runs the query and exits, while -q runs it and stays in the interactive session. -E uses Windows authentication (a trusted connection).

The Most Important Parameters for Automation

Parameter What it does
-i file.sql Runs a script file; several files can be given, separated by commas
-o result.txt Writes output to a file
-b Stops on error and returns a non-zero exit code
-v name=”value” Sets a scripting variable
-W, -s “,”, -h -1 Trims spaces, sets the separator, removes the header row (for CSV output)
-l seconds Login timeout
-A Connects through the Dedicated Admin Connection

-b is the most overlooked and most important parameter in automation. Without it, sqlcmd can exit as if it succeeded even when the script failed, and the scheduled task or CI/CD pipeline never sees the error.

sqlcmd -S SERVER -E -b -i deploy.sql -o deploy_log.txt
if ($LASTEXITCODE -ne 0) { Write-Error "Deployment failed, log: deploy_log.txt"; exit 1 }

Scripting Variables

To run the same script in different environments, pass values in from outside. Inside the script, variables are used as $(Name):

-- take_backup.sql
BACKUP DATABASE [$(DbName)]
TO DISK = N'$(BackupPath)$(DbName)_copy.bak'
WITH COPY_ONLY, COMPRESSION, CHECKSUM;
sqlcmd -S SERVER -E -b -i take_backup.sql -v DbName="SalesDB" BackupPath="D:\Backup\"

sqlcmd Commands: :r, :setvar, :connect, :on error

Besides T-SQL, sqlcmd recognizes its own commands that start with a colon. They keep large deployment scripts organized:

:on error exit
:setvar Environment "TEST"

PRINT N'Environment: $(Environment)';

-- Include other files in order
:r .\01_tables.sql
:r .\02_views.sql
:r .\03_procedures.sql

-- Switch to another server within the same script
:connect REPORTSERVER
SELECT @@SERVERNAME;

You can use these commands in SSMS too: with Query › SQLCMD Mode on, the query window understands sqlcmd syntax. That lets you try a script in SSMS first and then run it unchanged from the command line.

Encryption and Certificate Errors

Like the newer ODBC drivers, current sqlcmd versions encrypt the connection by default and validate the server certificate. If the server uses its own self-signed certificate, the connection fails with a certificate error. The -C parameter connects by trusting the certificate, but because it skips validation it’s only a temporary workaround.

Warning

Skipping certificate validation with -C, or putting the password on the command line with -P, makes scripts convenient but weakens security. A password on the command line shows up in the process list and in history files. Use Windows authentication (-E) where possible; if SQL authentication is required, supply the password through the SQLCMDPASSWORD environment variable or read it from a vault. The permanent fix is a trusted certificate on the server.

Our connection errors guide explains the background of certificate errors.

Practical Scenarios

  • Multi-server checks: a PowerShell loop that reads a server list from a file and runs the same check script on each one.
  • Deployment: scripts ordered with :r, and a safe release that stops at the first error with -b and :on error exit.
  • Scheduled jobs: maintenance scripts with output written to a file, in Agent CmdExec steps or Windows Task Scheduler.
  • In a crisis: connecting through the DAC with sqlcmd -S SERVER -E -A -d master while the server isn’t responding.
  • Exports: quick CSV output with -W -s "," -h -1. For large data transfers, bcp is the better tool.

Tip

If you work in PowerShell, the Invoke-Sqlcmd cmdlet in the SqlServer module returns results as objects; when you need to filter results, turn them into tables or pass them to other systems, that’s more practical than parsing text output.

A Microsoft tool that connects to SQL Server and runs T-SQL commands and script files from the command line. It’s used for automation, deployments and scheduled jobs.
The -b parameter stops at the first error and returns a non-zero exit code. The :on error exit command inside a script does the same.
Define them with -v Name=”value” on the command line or :setvar Name “value” inside the script, and use them as $(Name).
Current versions encrypt by default and validate the certificate. The permanent fix is a trusted certificate on the server; the -C parameter is a temporary workaround that skips validation.

SQL Server Automation

Turn repetitive work into reliable scripts

Aryasoft’s senior DBA team turns your maintenance, deployment and reporting tasks into scripts and jobs with error handling, logging and monitoring.

4.7/5