SQL Server command-line utilities let you manage databases directly from the terminal with powerful tools like `sqlcmd`, `bcp`, and `xp_cmdshell`. No GUI needed: perfect for automation, scripting, or quick fixes. First, ensure SQL Server is installed and accessible (usually as `sqlservr.exe` on Windows or `sql-server` as a service). For Linux/macOS, you’ll need the Microsoft SQL Server client tools installed. These tools handle backups, restores, schema changes, and more without opening Management Studio. Use them for critical tasks like restoring corrupted databases, exporting large datasets, or running.transact-SQL scripts programmatically.
What You'll Need
- SQL Server installed on your machine (Standard, Developer, or Express editions work; Enterprise adds advanced features).
- Administrator or sufficient permissions to run database operations.
- SQL Server client tools installed (for Linux/macOS). On Windows, the
sqlcmdtool comes with SQL Server 2016+. - Server credentials (username/password) for the database you want to work with.
- A text editor or IDE (optional but helpful for writing scripts).
Step-by-Step Guide
- Open Command Prompt as Administrator: Press Win + X, then select Windows Terminal (Admin) or Command Prompt (Admin). This ensures all tools have the necessary permissions.
-
Connect to a SQL Server instance using
sqlcmd: Run this command, replacing placeholders with your details:sqlcmd -S [server_name] -U [username] -P [password] -d [database_name]Example:sqlcmd -S localhost -U sa -P YourPassword123 -d NorthwindIf the server is remote, use-S [server_ip_or_hostname]. For named instances (e.g., "SQLEXPRESS"), append-S [instance_name]. -
Run a simple query:
Type a query like
SELECT TOP 5 * FROM Customers;and press Enter. To exit, typeEXITorQUIT. -
Backup a database:
Use the
BACKUP DATABASEcommand:BACKUP DATABASE [database_name] TO DISK = 'C:\backup_file.bak'Replace[database_name]and the path. For encrypted backups (SQL Server 2016+), add:WITH ENCRYPTION = OFF(orONfor encryption). To verify the backup was successful, run:RESTORE FILESET = 0 FROM BACKUP (NAME = 'BackupName') WITH NOUNLOAD -
Restore a database from backup:
First, drop the target database if it exists:
DROP DATABASE [database_name]Then restore:RESTORE DATABASE [database_name] FROM DISK = 'C:\backup_file.bak' WITH REPLACEAddNOUNLOADto keep files in the original location. -
Export data to CSV using
bcp: Export a table:bcp [table_name] queryout "SELECT * FROM [schema].[table_name]" -c -t, -S [server_name] -U [username] -P [password]Example:bcp Customers queryout "SELECT CustomerID, CompanyName FROM Customers" -c -t, -S localhost -U sa -P YourPassword123To import (reverse CSV to SQL):bcp [table_name] in "C:\export.csv" -c -t, -S [server_name] -U [username] -P [password] -
Run a stored procedure:
Query a stored procedure directly:
EXEC [schema].[stored_procedure_name] @param1 = 'value', @param2 = 123Example:EXEC usp_GetCustomerOrders @CustomerID = 1001 -
Fix a corrupted database:
Use
CHECKPOINTandDBCC CHECKDB:CHECKPOINTflushes transaction logs. Then run:DBCC CHECKDB (@database_name)For a corrupted table, use:DBCC CHECKTABLE ([schema].[table_name]) WITH ALL_ERRORMSGSTo repair, run:DBCC REPAIRCONTIG(for fragmentation) or:DBCC REPAIR ((replace error_number with the output from CHECKDB)., ) -
Create and drop a temporary table:
Create:
CREATE TABLE #TempTable (ID INT, Name VARCHAR(100))Drop:DROP TABLE #TempTable
Common Mistakes
-
Permission errors: Ensure the user has
ALTER,SELECT, orDBAroles. On Windows, verify the user is in thesysadminrole if needed. Use:sp_addrolemember N'db_owner', N'[username]', N'dbo'to grant ownership. -
Server not responding: Check if SQL Server is running. On Windows, open Services, find
SQL Server (MSSQLSERVER)or your instance name, and restart it if stopped. For remote servers, verify the firewall allows port 1433 (default) or the custom port you configured. -
Backups failing with "file not found": Double-check the backup path exists and the file isn’t open in another program. For encrypted backups, ensure the encryption key is valid (use
BACKUP KEY TO FILEto manage it). -
Commands ignoring parameters: Some older SQL Server versions require a semicolon after every statement (e.g.,
GOor;). Modern versions use;for individual statements.
Tips
-
Use aliases for frequent commands: Save common queries in a file (e.g.,
backup.sql) and run them with:sqlcmd -i backup.sqlExample backup script:BACKUP DATABASE [Northwind] TO DISK = 'C:\backups\Northwind.bak' RUN CHECKPOINT -
Pipe commands for efficiency: Export data to CSV and load it later in one step:
sqlcmd -S localhost -U sa -P Password -d Northwind -Q "SELECT * FROM Orders" | bcp Orders queryout -c -t, -S localhost -U sa -P Password -
Monitor performance with DBCC: Run
DBCC SHOWCONNECTIONSto check active connections. UseDBCC LOGINFOto inspect transaction logs. -
Use parameterized queries to avoid SQL injection. For example:
EXEC [schema].[usp_GetCustomer] @CustomerID = ?and pass the value later insqlcmd:sqlcmd -S localhost -Q "EXEC [dbo].[usp_GetCustomer] @CustomerID = 1001" -
Backup the log file for critical databases. Use:
BACKUP LOG [database_name] TO DISK = 'C:\backups\log.bak'to ensure recoverability.
Troubleshooting
-
Connection fails with "Login failed":
- Verify the username/password is correct (try the default
saif unsure). - Check if the user exists in SQL Server. Create it if missing:
USE master; EXEC sp_addlogin 'NewUser', 'Password'; EXEC sp_adduser 'NewUser', 'NewUser'Replace'NewUser'and'Password'. - Ensure the user has a password (not empty).
- For Windows Authentication, use
-Wflag:sqlcmd -S localhost -W -U domain\usernameReplacedomain\usernamewith your account.
- Verify the username/password is correct (try the default
-
Command-line tool not found:
- On Windows, ensure SQL Server is installed. Add the path to
System Environment Variables > PATH(e.g.,C:\Program Files\Microsoft SQL Server\150\Tools\Binn\ManagementStudio). - On Linux/macOS, install the client tools via:
sudo apt-get install mssql-tools(Debian/Ubuntu) orbrew install mssql-tools(macOS via Homebrew). - Verify the executable exists. For
sqlcmd, check:where sqlcmd(Windows) orwhich sqlcmd(Linux/macOS).
- On Windows, ensure SQL Server is installed. Add the path to
-
Backup failed with "Logical Reuse Not Allowed":
- Run
CHECKPOINTbefore backups to clear the log. - Check if the database is in recovery mode. Switch it to simple/reporting mode:
ALTER DATABASE [database_name] SET RECOVERY SIMPLE - For large databases, use
WITH MULTIPLE_SECTIONSfor partial backups.
- Run
-
Bulk Copy Program (bcp) fails:
- Ensure the server allows remote connections if running from a different machine. Edit
sqlserver.configand setto allow remote access.]]> - Verify the username/password are correct. For Windows Authentication, use:
bcp [table_name] queryout ... -W -S [server_name](no password required, but must have proper permissions). - Check for encoding mismatches. Use
-Tfor tab-separated values or specify encoding:-E(ASCII) or-r(UTF-8).
- Ensure the server allows remote connections if running from a different machine. Edit
-
DBCC commands return "Operation must use updateable cursor":
Use
WITH SHOW_STATISTICSto debug:DBCC CHECKDB ([schema].[table_name]) WITH SHOW_STATISTICSFor specific errors, refer to theerror_numberdocumentation.
Frequently Asked Questions
How do I list all databases from the command line?
Run sqlcmd -S [server_name] -U [username] -P [password] -Q "SELECT name FROM sys.databases" in Command Prompt. Replace placeholders with your server details. For all instances on the local machine, use:
sqlcmd -S localhost -Q "SELECT name FROM sys.databases"
What’s the difference between bcp and sqlcmd for data export?
bcp is optimized for bulk data transfer (faster for large datasets) and supports formats like CSV, XML, or delimited text. sqlcmd is better for interactive queries or running complex scripts. For example:
bcp Customers queryout "SELECT * FROM Customers" -c -t, -S localhost -U sa -P Password
exports all data, while sqlcmd would require a query like -Q "SELECT * FROM Customers".
Can I use SQL Server command-line tools on Linux?
Yes, if you have the Microsoft SQL Server client tools installed. On Debian/Ubuntu:
sudo apt-get install mssql-tools
On macOS:
brew install mssql-tools
Use the same commands as on Windows (e.g., sqlcmd), but verify paths in your environment.
Why does DBCC CHECKDB say "Database is in RECOVERY MODE"?
This is normal for databases with transaction logs. To switch recovery mode, use:
ALTER DATABASE [database_name] SET RECOVERY SIMPLE
for simple recovery (no log backups) or:
ALTER DATABASE [database_name] SET RECOVERY FULL
for full recovery (requires log backups). Always back up logs before changing recovery mode.
How do I remove a stored procedure?
Drop the procedure with:
DROP PROCEDURE [schema].[stored_procedure_name]
Example:
DROP PROCEDURE dbousp_GetCustomerOrders
Replace the schema and name with your target. For system procedures, use sys. instead of dbo.
Can I schedule SQL Server commands to run automatically?
Yes, use Windows Task Scheduler or Linux cron to run SQL scripts. Example Windows task:
- Create a batch file (e.g.,
backup.sql.bat):sqlcmd -S localhost -U sa -P Password -i "C:\scripts\backup.sql" - Schedule it in Task Scheduler with admin rights to run at intervals.
crontab -e and add a line like:
0 2 * * * /usr/bin/sqlcmd -S localhost -U sa -P Password -i /path/to/script.sql
to run daily at 2 AM.