Beyond Full Backups: Exploring Differential & Transaction Log Backups
Backing Up SQL Server Databases with Command Line Scripts
We can achieve this using the sqlcmd
utility and the BACKUP DATABASE
Transact-SQL (T-SQL) statement. Here's an example script with explanations:
sqlcmd -S SERVERNAME -U USERNAME -P PASSWORD -Q "BACKUP DATABASE DATABASE_NAME TO DISK = 'BACKUP_LOCATION\DATABASE_NAME_BACKUP.bak'"
Explanation:
sqlcmd
: This is the command-line tool used to execute T-SQL statements on SQL Server.-S SERVERNAME
: This specifies the name of the SQL Server instance you want to connect to.-U USERNAME
: This specifies the username with access to the database.-P PASSWORD
: This specifies the password for the provided username.-Q
: This tellssqlcmd
to execute the following quoted string as a T-SQL statement."BACKUP DATABASE DATABASE_NAME TO DISK = 'BACKUP_LOCATION\DATABASE_NAME_BACKUP.bak'"
: This is the T-SQL statement that performs the backup.
Breakdown of the T-SQL statement:
BACKUP DATABASE
: This keyword initiates the backup operation.DATABASE_NAME
: This is the name of the database you want to back up.TO DISK
: This specifies that the backup will be stored as a file.'BACKUP_LOCATION\DATABASE_NAME_BACKUP.bak'
: This defines the path and filename for the backup file. Replace "BACKUP_LOCATION" with the actual folder where you want to store the backup, and modify "DATABASE_NAME_BACKUP.bak" to your desired filename extension (typically ".bak").
Examples:
- To backup the "master" database to
C:\Backups\master_backup.bak
:
sqlcmd -S SERVERNAME -U USERNAME -P PASSWORD -Q "BACKUP DATABASE master TO DISK = 'C:\Backups\master_backup.bak'"
- To backup the "AdventureWorks2019" database with a timestamp to
D:\DailyBackups
:
sqlcmd -S SERVERNAME -U USERNAME -P PASSWORD -Q "BACKUP DATABASE AdventureWorks2019 TO DISK = 'D:\DailyBackups\AdventureWorks2019_%date:~-10,2%%date:~-7,2%%date:~-4,4%.bak'"
This example uses environment variables to automatically append the current date to the backup filename, ensuring unique backups each day.
Related Issues and Solutions:
- Permissions: Ensure the user you specify in the script has appropriate permissions to access the database and create files in the backup location.
- Scheduling: While this script allows manual backup execution, consider scheduling regular backups using Windows Task Scheduler or SQL Server Agent for automated backups.
- Backup Types: This example demonstrates a full database backup. You can explore other backup options like differential or transaction log backups for specific scenarios using the
WITH
clause in theBACKUP DATABASE
statement.
Remember to replace placeholders like SERVERNAME
, USERNAME
, PASSWORD
, DATABASE_NAME
, and BACKUP_LOCATION
with your actual values before running the script.
sql-server command-line scripting