- Microsoft SQL Server Command Line Tool
- Open a command line
- Database connection
- Enter a search
- Execution of a request
- Exit SQLCMD
Microsoft SQL Server Command Line Tool
Microsoft SQL Server provides users with a variety of graphical user interfaces for extracting and manipulating data and for configuring SQL Server databases. Sometimes, though, it’s easier to work from the old-fashioned command line. Whether you’re looking for a quick and dirty way to run an SQL query, or you want to include SQL statements in a Windows script file, SQLCMD can help you achieve your goal. This article assumes that the Microsoft AdventureWorks sample database is already installed.
Open a command line
To run SQLCMD, you must first open a Windows command-line tool. In Windows XP, click Get started † Run and then type cmd in the text box, then click Okay † In Windows Vista, click Windows enter cmd in the field Search and press Enter †
You should see the Windows command prompt.
Once the command prompt is open, use the SQLCMD utility to connect to the database. In this example, we’re connecting to the AdventureWorks2014 database, so we’ll use the command:
sqlcmd -d AdventureWorks2014
This uses the default Windows credentials to connect to your database. You can also specify a username with the -U flag and a password with the -P flag. For example, you can connect to a database with username “mike” and password “goirish” using the following command line:
sqlcmd -U майк -P goirish -d AdventureWorks2014
Enter a search
Start typing the SQL statement at the 1> prompt. You can use as many lines as you want for your search by pressing the key. to push Enter after each line. SQL Server will not execute your request until it receives an explicit statement.
In this example, we enter this query:
Execution of a request
When you are ready to execute your request, enter the command TO GO in a new command line in SQLCMD and press Enter † SQLCMD will perform your search and display the results on the screen.
When you are ready to exit SQLCMD, enter the command: EXIT on an empty command prompt to return to the Windows command prompt.