SQLCMD Step-by-Step Tutorial

Microsoft SQL server command line utility

typing on the laptop computer
lechatnoir / Getty Images

Microsoft SQL Server provides users with a variety of rich graphical user interfaces for retrieving and manipulating data and configuring SQL Server databases. However, sometimes it’s just easier to work from the old-fashioned command line. 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 allows you to meet your goal. This article assumes you already have Microsoft's AdventureWorks Sample Database installed. 

of 05

Opening a Command Prompt

Command Prompt

In order to run SQLCMD, you must first open a Windows command line utility. In Windows XP, click Start > Run and then type CMD in the text box before clicking OK. In Windows Vista, click the Windows button, type CMD into the Search box and press Enter.

You should see a Windows command prompt.

of 05

Connecting to the Database

Connect to the database

Once you have a command prompt open, use the SQLCMD utility to connect to the database. In this example, we're connecting to the AdventureWorks2014 database, so we use the command:

sqlcmd -d AdventureWorks2014

This uses the default Windows credentials to connect to your database. You may also specify a username using the -U flag and a password using the -P flag. For example, you could connect to the database using the username "mike" and password "goirish" with the following command line:

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

Entering a Query

SQL Query

Begin typing a SQL statement at the 1> prompt. You can 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

Executing 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

Exiting SQLCMD

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