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.

01
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.

02
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
03
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:

 SELECT *
FROM HumanResources.shift
04
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.

05
of 05

Exit SQLCMD

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