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 sqlcmd tool 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

  1. 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.
  2. 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 Northwind If the server is remote, use -S [server_ip_or_hostname]. For named instances (e.g., "SQLEXPRESS"), append -S [instance_name].
  3. Run a simple query: Type a query like SELECT TOP 5 * FROM Customers; and press Enter. To exit, type EXIT or QUIT.
  4. Backup a database: Use the BACKUP DATABASE command: 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 (or ON for encryption). To verify the backup was successful, run: RESTORE FILESET = 0 FROM BACKUP (NAME = 'BackupName') WITH NOUNLOAD
  5. 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 REPLACE Add NOUNLOAD to keep files in the original location.
  6. 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 YourPassword123 To import (reverse CSV to SQL): bcp [table_name] in "C:\export.csv" -c -t, -S [server_name] -U [username] -P [password]
  7. Run a stored procedure: Query a stored procedure directly: EXEC [schema].[stored_procedure_name] @param1 = 'value', @param2 = 123 Example: EXEC usp_GetCustomerOrders @CustomerID = 1001
  8. Fix a corrupted database: Use CHECKPOINT and DBCC CHECKDB: CHECKPOINT flushes transaction logs. Then run: DBCC CHECKDB (@database_name) For a corrupted table, use: DBCC CHECKTABLE ([schema].[table_name]) WITH ALL_ERRORMSGS To repair, run: DBCC REPAIRCONTIG (for fragmentation) or: DBCC REPAIR (, ) (replace error_number with the output from CHECKDB).
  9. 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, or DBA roles. On Windows, verify the user is in the sysadmin role 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 FILE to manage it).
  • Commands ignoring parameters: Some older SQL Server versions require a semicolon after every statement (e.g., GO or ;). 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.sql Example 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 SHOWCONNECTIONS to check active connections. Use DBCC LOGINFO to inspect transaction logs.
  • Use parameterized queries to avoid SQL injection. For example: EXEC [schema].[usp_GetCustomer] @CustomerID = ? and pass the value later in sqlcmd: 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

  1. Connection fails with "Login failed":
    1. Verify the username/password is correct (try the default sa if unsure).
    2. 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'.
    3. Ensure the user has a password (not empty).
    4. For Windows Authentication, use -W flag: sqlcmd -S localhost -W -U domain\username Replace domain\username with your account.
  2. Command-line tool not found:
    1. 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).
    2. On Linux/macOS, install the client tools via: sudo apt-get install mssql-tools (Debian/Ubuntu) or brew install mssql-tools (macOS via Homebrew).
    3. Verify the executable exists. For sqlcmd, check: where sqlcmd (Windows) or which sqlcmd (Linux/macOS).
  3. Backup failed with "Logical Reuse Not Allowed":
    1. Run CHECKPOINT before backups to clear the log.
    2. Check if the database is in recovery mode. Switch it to simple/reporting mode: ALTER DATABASE [database_name] SET RECOVERY SIMPLE
    3. For large databases, use WITH MULTIPLE_SECTIONS for partial backups.
  4. Bulk Copy Program (bcp) fails:
    1. Ensure the server allows remote connections if running from a different machine. Edit sqlserver.config and set ]]> to allow remote access.
    2. 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).
    3. Check for encoding mismatches. Use -T for tab-separated values or specify encoding: -E (ASCII) or -r (UTF-8).
  5. DBCC commands return "Operation must use updateable cursor": Use WITH SHOW_STATISTICS to debug: DBCC CHECKDB ([schema].[table_name]) WITH SHOW_STATISTICS For specific errors, refer to the error_number documentation.

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:

  1. Create a batch file (e.g., backup.sql.bat):
    sqlcmd -S localhost -U sa -P Password -i "C:\scripts\backup.sql"
  2. Schedule it in Task Scheduler with admin rights to run at intervals.
On Linux, use: 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.