Backup & Restore API Reference
Overview
The Backup and Restore APIs allow developers to programmatically create database backups, restore databases, and manage backup sets using T‑SQL or the SQL Server Management Objects (SMO) library. These APIs are essential for automated maintenance, disaster recovery, and cloud migration scenarios.
Syntax
T‑SQL Backup Syntax
BACKUP DATABASE<database_name>TO DISK =<file_path>[ WITH<options>];
T‑SQL Restore Syntax
RESTORE DATABASE<database_name>FROM DISK =<file_path>[ WITH<options>];
SMO Backup Example (C#)
var server = new Server(@"localhost\SQLEXPRESS");
var backup = new Backup{
Action = BackupActionType.Database,
Database = "AdventureWorks"
};
backup.Devices.AddDevice(@"C:\Backups\AdventureWorks.bak", DeviceType.File);
backup.SqlBackup(server);
Common Parameters
| Parameter | Description |
|---|---|
NAME | Name of the backup set. |
INIT | Overwrite existing backup file. |
COMPRESSION | Enable backup compression (SQL Server 2008+). |
STATS | Display progress every n percent. |
FILEGROUP | Backup/restore a specific filegroup. |
Practical Examples
Full Database Backup with Compression
BACKUP DATABASE AdventureWorks TO DISK = N'C:\Backups\AdventureWorks_Full.bak' WITH COMPRESSION, STATS = 10;
Differential Backup
BACKUP DATABASE AdventureWorks TO DISK = N'C:\Backups\AdventureWorks_Diff.bak' WITH DIFFERENTIAL, STATS = 5;
Restore with Recovery
RESTORE DATABASE AdventureWorks
FROM DISK = N'C:\Backups\AdventureWorks_Full.bak'
WITH RECOVERY, MOVE 'AdventureWorks_Data' TO 'D:\Data\AdventureWorks.mdf',
MOVE 'AdventureWorks_Log' TO 'D:\Log\AdventureWorks.ldf';
Important Notes
- Always test restore procedures on a non‑production server.
- For large databases, consider
FILESTREAMorFILEGROUPbackups. - Enable
Backup Compression Defaultat the instance level for automatic compression. - Use
WITH CHECKSUMto verify backup integrity.