SQL Server command line tools allow you to interact with your database without a graphical user interface (GUI) like SQL Server Management Studio (SSMS). You can achieve this primarily using sqlcmd for executing queries and bcp (Bulk Copy Program) for importing or exporting large datasets. These tools are essential for automating tasks via scripts, managing remote servers, and performing high-speed data migrations.
What You'll Need
- A computer running Windows, macOS, or Linux.
- An active SQL Server instance (local or remote) that you have permission to access.
- Administrative privileges on your local machine to install the tools.
- The server name or IP address and your authentication credentials (Windows Authentication or a SQL Server login).
Step-by-Step
- Install the Command Line Tools: Download and install the Microsoft Command Line Utilities for SQL Server. Depending on your OS, you can install these via the official Microsoft download center or through a package manager (such as Homebrew on macOS or apt-get on Linux). Ensure you also install the ODBC Driver for SQL Server, as the command line tools rely on it to communicate with the database.
- Open your Terminal: Launch the Command Prompt (cmd.exe) or PowerShell on Windows, or the Terminal app on macOS/Linux.
- Connect using sqlcmd: Use the following syntax to establish a connection. Labels and flags may vary slightly depending on the version of the tools installed.
- For Windows Authentication (local):
sqlcmd -S ServerName - For SQL Server Authentication:
sqlcmd -S ServerName -U Username -P Password
ServerNamewith your actual server instance name (e.g.,localhostorlocalhost\SQLEXPRESS). - For Windows Authentication (local):
- Execute a SQL Query: Once connected, you will see a prompt (1>). Type your SQL statement, then type
GOon a new line and press Enter to execute it.
Example:SELECT name FROM sys.databases;GO - Run a Script File: To execute a pre-written .sql file instead of typing manually, use the
-iflag from the standard command prompt (not from within the sqlcmd session):sqlcmd -S ServerName -i C:\scripts\my_script.sql - Export Data using bcp: To move data from a table to a file, use the bcp utility.
Example:bcp DatabaseName.dbo.TableName out C:\data\export.txt -c -T
The-cflag specifies character data, and-Tspecifies a trusted connection (Windows Authentication). - Import Data using bcp: To move data from a file into a table, use the
incommand.
Example:bcp DatabaseName.dbo.TableName in C:\data\export.txt -c -T - Exit the Tool: To leave the sqlcmd prompt and return to your terminal, type
QUITand press Enter.
Common Mistakes
- Forgetting the GO command: In sqlcmd, typing a query and pressing Enter does not execute it; it simply adds the line to the buffer. You must type
GOon a separate line to send the batch to the server. - Incorrect Instance Names: Users often forget to include the instance name for named instances (e.g., using
localhostinstead oflocalhost\SQLEXPRESS), leading to connection timeouts. - Permission Issues: Attempting to run bcp imports or exports to folders where the current user does not have write permissions (like the root C:\ drive) will cause the operation to fail.
- Mixing Authentication Types: Using
-T(Trusted Connection) while simultaneously providing a username-Uand password-Pcan cause conflicts or errors.
Tips
- Output to File: Use the
-oflag with sqlcmd to save the results of a query directly to a text file:sqlcmd -S ServerName -Q "SELECT GETDATE()" -o output.txt. - Use -Q for Single Commands: If you only need to run one command and exit immediately, use
-Qinstead of-q. This executes the query and closes the session automatically. - Bypass the Prompt: For automation, always use the
-i(input file) or-Q(query) flags so the script does not wait for manual user input. - Check Versions: If you encounter unexpected behavior, run
sqlcmd -?to see the full list of available switches and flags for your specific version.
Troubleshooting
If the command line tools do not work as expected, follow these steps in order:
- Verify the Service: Ensure the SQL Server service is actually running. Open the SQL Server Configuration Manager and check that the "SQL Server (MSSQLSERVER)" or named instance service is in the "Running" state.
- Check Network Protocols: If connecting to a remote server, ensure that "TCP/IP" is enabled in the SQL Server Configuration Manager under SQL Server Network Configuration > Protocols for [InstanceName].
- Test the Firewall: Ensure that the port used by SQL Server (default is 1433) is open in the Windows Firewall or any network security groups.
- Verify ODBC Driver: If you receive a "driver not found" error, reinstall the latest Microsoft ODBC Driver for SQL Server.
- Check Credentials: Try connecting via SQL Server Management Studio (SSMS) first. If you cannot connect via SSMS, the issue is likely with your credentials or server settings, not the command line tools.
Frequently Asked Questions
Can I use sqlcmd on a Mac or Linux?
Yes. Microsoft provides versions of the sqlcmd and bcp tools for both macOS and Linux. You will need to install the ODBC driver for your specific operating system first.
What is the difference between sqlcmd and bcp?
sqlcmd is used for executing T-SQL queries, managing database objects, and administrative tasks. bcp is a specialized tool designed specifically for high-performance bulk importing and exporting of data.
How do I handle passwords securely in scripts?
Avoid putting passwords in plain text in scripts. Instead, use Windows Authentication (-T) or use environment variables to pass the password to the command line.
Why does bcp say "Invalid column length"?
This usually happens when the data in your source file is wider than the defined column width in the destination table. Check your table schema and the format of your source file.
Can sqlcmd be used for database backups?
Yes. You can execute the BACKUP DATABASE command through sqlcmd just as you would in a query window in SSMS.