Yes, you can manage SQL Server 2014 entirely from the command line using the built-in SQLCMD utility. This is achieved by opening a standard Windows Command Prompt, navigating to the installation directory, and running the sqlcmd executable with specific parameters to connect to, query, and manipulate your database.

What You'll Need

  • A computer running Windows with SQL Server 2014 installed.
  • A user account with permissions to connect to the target SQL Server instance.
  • A command prompt window (cmd.exe).
  • Basic knowledge of SQL syntax for querying data.

Step-by-Step

  1. Open the Command Prompt: Press the Windows Key + R to open the Run dialog box. In the text field, type cmd and press Enter. This will launch the standard Command Prompt.
  2. Navigate to the SQL Server Utility Directory: By default, the SQLCMD executable is located in the SQL Server installation folder. You can navigate there using the cd (change directory) command. For example, if SQL Server is installed on the C: drive, type the following command and press Enter:
    cd /d "C:\Program Files\Microsoft SQL Server\140\Tools\Binn"

    Note: The folder path ends with 140, which corresponds to SQL Server 2014. If you installed SQL Server to a different drive or path, adjust the command accordingly.

  3. Connect to the SQL Server Instance: To connect, type the sqlcmd command followed by the server name and authentication details. The basic syntax is:
    sqlcmd -S ServerName\InstanceName -U Username -P Password

    For example, if your server is named MY-PC and you want to use the default instance, you would use:

    sqlcmd -S MY-PC\SQLEXPRESS -U sa -P MySecurePassword123

    Important: The backslash (\) is crucial for separating the server name from the instance name. If you are using the default instance on the local computer, you can often omit the instance name, though it is safer to include it.

  4. Verify the Connection: Once you press Enter, you should see a new prompt appear. It will look like 1> or 1>>. This indicates that you are now connected and ready to execute commands.
  5. Execute a Simple Query: At the prompt, type a SQL query and press Enter. For example, to see a list of all databases on the server, enter:
    SELECT name FROM sys.databases;

    Pressing Enter will execute the query. The results will be displayed below the command, showing a numbered list of your databases.

  6. Save the Output to a File: To save the results of a query to a text file, use the -o (output) parameter. For example, to save the list of databases to a file named dblist.txt:
    sqlcmd -S MY-PC\SQLEXPRESS -U sa -P MySecurePassword123 -Q "SELECT name FROM sys.databases;" -o "C:\temp\dblist.txt"

    The -Q parameter tells sqlcmd to execute the query and then immediately exit, which is useful for command-line scripting.

  7. Run a Script from a File: Instead of typing commands manually, you can run a pre-written SQL script. Save your SQL commands in a file (e.g., update_stats.sql). To run this file, use the -i (input) parameter:
    sqlcmd -S MY-PC\SQLEXPRESS -U sa -P MySecurePassword123 -i "C:\scripts\update_stats.sql"

    This is the most common use case for command-line utilities, allowing for automated maintenance tasks.

  8. Manage Backup and Restore: You can also perform administrative tasks like backups and restores. For example, to create a backup of a database named MyDatabase:
    sqlcmd -S MY-PC\SQLEXPRESS -U sa -P MySecurePassword123 -Q "BACKUP DATABASE MyDatabase TO DISK='C:\backups\MyDatabase.bak' WITH FORMAT;"

    This command connects to the server, executes the backup command, and then closes the connection.

  9. Exit the Command Prompt: When you are finished, type EXIT and press Enter to return to the standard Windows command prompt.

Common Mistakes

  • Incorrect Server Name Syntax: A very common error is omitting the backslash (\) or using a forward slash (/). The correct syntax is ServerName\InstanceName. For example, MyServer\MyInstance. If you are using the default instance, you can often omit the instance name, but it is recommended to include it for clarity.
  • Quoting Passwords: If your password contains special characters like spaces or single quotes, it is crucial to wrap the entire password in double quotes. For example: -P "My Password with 'quotes'". Forgetting the quotes will cause the command to fail at the point where the special character is encountered.
  • Forgetting the Semicolon: In SQL Server, every SQL statement must end with a semicolon (;). If you forget the semicolon, the command prompt will wait for you to continue typing, thinking the statement is incomplete.
  • Running as Administrator: In some cases, you may need to run the Command Prompt as an administrator to execute certain commands, especially those related to backups or system configuration. Right-click on the Command Prompt shortcut and select “Run as administrator.”

Tips

  • Use the -E Parameter for Windows Authentication: Instead of specifying a username and password with the -U and -P parameters, you can use the -E (or -trusted) parameter to connect using your current Windows user account. This is often simpler and more secure. For example: sqlcmd -S MY-PC\SQLEXPRESS -E.
  • Enable Tab Completion: To speed up typing, you can enable tab completion for server names and database names. This is done by adding the -t (timeout) parameter to the command. For example: sqlcmd -S MY-PC\SQLEXPRESS -t 30. This will set a timeout of 30 seconds, but also enables tab completion.
  • Use the -b Parameter to Return Error Codes: If you are running sqlcmd in a batch script, you can use the -b parameter to have sqlcmd return a non-zero exit code if any of the commands it runs fail. This allows your script to handle errors gracefully.
  • Use the -y Parameter to Set Row Limit: By default, sqlcmd will display all rows returned by a query. If you are only interested in the first few rows, you can use the -y parameter to set a row limit. For example: sqlcmd -S MY-PC\SQLEXPRESS -Q "SELECT * FROM MyTable;" -y 5 will only display the first 5 rows.

Troubleshooting

If you encounter an error message when trying to connect or execute a command, the first step is to check the error message carefully. The error message will usually indicate the specific problem, such as a login failure, a connection timeout, or a permission issue.

Common troubleshooting steps include:

  • Verify the Server Name: Ensure that you are using the correct server name. You can find the server name in the SQL Server Configuration Manager. Open SQL Server Configuration Manager, expand the “SQL Server Network Configuration” node, and look at the “Protocols for [YourServerName]” node.
  • Check SQL Server Services: Ensure that the SQL Server service is running. Open SQL Server Configuration Manager, expand the “SQL Server Services” node, and check the status of the “SQL Server ([YourServerName])” service. If it is not running, right-click on it and select “Start.”
  • Check Firewall Settings: Ensure that the necessary ports for SQL Server are open in your firewall. SQL Server typically uses port 1433 for TCP/IP connections. You may need to add an exception for this port in your firewall settings.
  • Check Login Credentials: Ensure that you are using the correct username and password. If you are using Windows Authentication, ensure that your Windows user account has permissions to connect to the SQL Server instance.
  • Check for SQLCMD Availability: Ensure that the SQLCMD utility is installed and accessible. You can verify this by typing sqlcmd -? in the command prompt. If the command is not recognized, it means the SQLCMD utility is not in your system's PATH environment variable. You may need to add the path to the SQLCMD executable to your system's PATH variable.

Frequently Asked Questions

Can I use sqlcmd on a remote server?
Yes, you can use sqlcmd to connect to a remote SQL Server instance. You simply need to provide the remote server's name or IP address in the -S parameter. For example: sqlcmd -S 192.168.1.100\SQLEXPRESS -U sa -P MyPassword.
How do I pass a password containing a space to sqlcmd?
You must wrap the entire password in double quotes. For example: sqlcmd -S MyServer -U sa -P "My Password 123".
What is the difference between -Q and -i?
The -Q parameter is used to execute a query directly from the command line. The -i parameter is used to execute a SQL script from a file.
How can I automate sqlcmd tasks?
You can automate sqlcmd tasks by creating a batch file (.bat) that contains the sqlcmd commands. You can then schedule the batch file to run automatically using the Windows Task Scheduler.
Why am I getting a “Login failed for user” error?
This error usually means that the username or password you provided is incorrect, or that the user does not have permission to connect to the server. You can verify this by using the SQL Server Management Studio (SSMS) to try to connect with the same credentials.