SQLCMD Step-by-Step Tutorial

Use the Command Prompt to interact with SQL Server in a text environment

typing on the laptop computer
lechatnoir / Getty Images

Microsoft SQL Server offers rich graphical user interfaces for retrieving and manipulating data and configuring SQL Server databases. However, sometimes it’s just easier to work from a text-based command interpreter. Whether you’re looking for a quick-and-dirty way to execute a SQL query or wish to include SQL statements in a Windows script file, SQLCMD supports this type of interaction.

This procedure works for all versions of Windows and SQL Server. However, SQL Server runtimes must be installed on the Windows computer. On a server, this process is usually automatic. To connect to a remote SQL Server with a local Windows machine, use different connection procedures.

of 05

Open the Command Prompt

Command Prompt

SQLCMD—a text interface into SQL Server—requires a shell session. Run Command Prompt by pressing Win+R and typing CMD or launching it through the Start menu.

SQL Server does not offer its own shell environment.

Also, use Command Prompt rather than the newer PowerShell.

of 05

Connect to the Database

Connect to the database

Use the SQLCMD utility to connect to the database:

sqlcmd -d databasename

This command uses the default Windows credentials to connect to the database specified by databasename. You may also specify a username using the -U flag and a password using the -P flag. For example, connect to the HumanResources database using the username mike and password goirish with the following command:

sqlcmd -U mike -P goirish -d HumanResources
of 05

Enter a Query

SQL Query

Begin typing a SQL statement at the 1> prompt. Use as many lines as you want for your query, pressing the Enter key after each line. SQL Server does not execute your query until explicitly instructed to do so.
In this example, we enter this query:

FROM HumanResources.shift
of 05

Execute the Query

Execute the query

When you are ready to execute your query, type the command GO on a new command line within SQLCMD and press Enter. SQLCMD executes your query and displays the results on the screen.

of 05


When you are ready to exit SQLCMD, type the command EXIT on a blank command line to return to the Windows command prompt.

mla apa chicago
Your Citation
Chapple, Mike. "SQLCMD Step-by-Step Tutorial." ThoughtCo, Dec. 6, 2021, thoughtco.com/sqlcmd-step-by-step-1019881. Chapple, Mike. (2021, December 6). SQLCMD Step-by-Step Tutorial. Retrieved from https://www.thoughtco.com/sqlcmd-step-by-step-1019881 Chapple, Mike. "SQLCMD Step-by-Step Tutorial." ThoughtCo. https://www.thoughtco.com/sqlcmd-step-by-step-1019881 (accessed June 7, 2023).