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.
Open the Command Prompt
:max_bytes(150000):strip_icc():format(webp)/commandprompt-5bd0e4f2c9e77c00510df1b5.jpg)
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.
Connect to the Database
:max_bytes(150000):strip_icc():format(webp)/connecttodatabase-5bd0e58146e0fb00519e9b0e.jpg)
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
Enter a Query
:max_bytes(150000):strip_icc():format(webp)/select-5bd0e6e346e0fb00512f73c1.jpg)
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
Execute the Query
:max_bytes(150000):strip_icc():format(webp)/execute-5bd0e76846e0fb0026ff8894.jpg)
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.
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.