SQL Server Script to Backup All Databases to Disk

An instance with thirty user databases needs thirty full backups, and writing thirty BACKUP DATABASE statements by hand means a new database is missed the day someone creates it. This T-SQL script reads sys.databases, selects every online user database and writes one compressed, checksummed full backup per database to a folder, each with the date and time in the filename.

Purpose and Overview

Backing up every user database with one job step and no list to maintain means reading the list from the instance itself. sys.databases has a row for each database, and its state column says whether the database can be backed up right now. The script keeps the rows that are user databases and online, then runs BACKUP DATABASE against each name in turn.

The output is a set of .bak files named DatabaseName_YYYYMMDD_HHMM_db_full.bak. The timestamp sorts correctly as text, so a directory listing shows backups in the order they were taken, and a run at a different minute never reuses a name. Because the list is read at run time, a database created yesterday is included tonight without editing the job.

The script covers user databases only. The system databases are left out on purpose (see the performance notes), and it is a full backup, so under the full recovery model it has to be paired with transaction log backups.

Code Breakdown

Set @BackupFolder to a folder the SQL Server service account can write to, run the script in any database context, and read the progress messages. It must run outside a transaction.

 1SET NOCOUNT ON;
 2
 3DECLARE @BackupFolder NVARCHAR(260) = N'D:\SQLBackups\';  -- trailing backslash required
 4
 5-- Date and time stamp: yyyymmdd_hhmm
 6DECLARE @Now   DATETIME = GETDATE();
 7DECLARE @Stamp NVARCHAR(13) =
 8        CONVERT(NCHAR(8), @Now, 112) + N'_'
 9      + RIGHT(N'0' + CAST(DATEPART(HOUR,   @Now) AS NVARCHAR(2)), 2)
10      + RIGHT(N'0' + CAST(DATEPART(MINUTE, @Now) AS NVARCHAR(2)), 2);
11
12-- Online user databases, excluding database snapshots
13DECLARE @Dbs TABLE
14(
15    RowId  INT IDENTITY(1,1) PRIMARY KEY,
16    DbName SYSNAME NOT NULL
17);
18
19INSERT INTO @Dbs (DbName)
20SELECT   [name]
21FROM     sys.databases
22WHERE    [name] NOT IN (N'master', N'model', N'msdb', N'tempdb')
23  AND    state = 0                    -- ONLINE
24  AND    source_database_id IS NULL   -- not a database snapshot
25ORDER BY [name];
26
27DECLARE @RowId  INT = 1;
28DECLARE @MaxId  INT = (SELECT MAX(RowId) FROM @Dbs);
29DECLARE @DbName SYSNAME;
30DECLARE @File   NVARCHAR(512);
31DECLARE @Failed INT = 0;
32
33WHILE @RowId <= @MaxId
34BEGIN
35    SELECT @DbName = DbName FROM @Dbs WHERE RowId = @RowId;
36    SET @File = @BackupFolder + @DbName + N'_' + @Stamp + N'_db_full.bak';
37
38    BEGIN TRY
39        BACKUP DATABASE @DbName
40        TO DISK = @File
41        WITH CHECKSUM, COMPRESSION, STATS = 10;
42    END TRY
43    BEGIN CATCH
44        SET @Failed += 1;
45        PRINT N'Backup failed for ' + @DbName + N': ' + ERROR_MESSAGE();
46    END CATCH;
47
48    SET @RowId += 1;
49END;
50
51IF @Failed > 0
52    THROW 50000, N'One or more database backups failed. Read the messages above.', 1;

Folder and Timestamp

@BackupFolder is concatenated straight onto the filename, so the trailing backslash matters. The stamp starts from CONVERT(..., 112), the ISO style that returns yyyymmdd, and appends the hour and minute from DATEPART. RIGHT(N'0' + ..., 2) pads a single digit, so 9:05 becomes 0905 and not 95. A minute-level stamp is enough for a nightly job, but two runs in the same minute produce the same filename, which matters because of how BACKUP treats an existing file (see the performance notes).

Selecting the Databases

sys.databases returns one row per database. Three conditions pick the targets:

  • [name] NOT IN (...) leaves out the system databases master, model, msdb and tempdb by name, so the script does not depend on their database_id values.
  • state = 0 keeps only databases that are ONLINE. The other values are RESTORING (1), RECOVERING (2), RECOVERY_PENDING (3), SUSPECT (4), EMERGENCY (5) and OFFLINE (6), and the script skips all of them.
  • source_database_id IS NULL removes database snapshots, which have a row in sys.databases and a non-NULL source ID.

The names go into a table variable with an identity column so the loop can walk them by position. SYSNAME is the type SQL Server uses for object names. Sorting by name makes the order of backups predictable from one night to the next.

The Backup Statement

BACKUP DATABASE @DbName accepts a variable for the database name, and TO DISK = @File accepts a variable for the path, so no dynamic SQL is needed. Three options are set:

  • CHECKSUM verifies each page checksum as it is read and writes a checksum for the whole backup. The default is NO_CHECKSUM, so this has to be requested, and it can cost some throughput.
  • COMPRESSION compresses the backup. The default is no compression unless the instance-level backup compression default was changed, so the option is explicit here.
  • STATS = 10 prints a message at each 10 percent. The numbers are approximate and can overshoot slightly.

During a full backup SQL Server also writes enough of the transaction log to produce a consistent database when the backup is restored, so the backup is transactionally consistent while users keep working.

Failure Handling

BEGIN TRY ... END TRY catches errors of severity higher than 10 that do not close the connection, so one failing database does not end the loop. The CATCH block counts and prints the failure and the loop moves on. After the loop, THROW raises one error when @Failed is above zero, so a SQL Agent job step ends as failed and the alert fires instead of the job reporting success over missing backups. The statement before THROW ends in a semicolon, as THROW requires.

Key Benefits and Use Cases

  • No list to maintain. New databases are included on the next run, and databases that are offline or restoring are skipped.
  • Collision-free filenames. The date and time in the name keep each night's files apart, so a rolling archive needs no renaming step.
  • Page-level damage shows up early. CHECKSUM surfaces a page whose checksum does not verify at backup time, rather than at restore time.
  • Smaller files, shorter copy time. Compressed backups are smaller than uncompressed ones, and because less data is written to the device, they usually finish faster.
  • One result for the job. The final THROW turns a partial failure into a failed job step, which is what alerting keys on.
  • Dev and test refresh. The same folder of files is the source for restoring a set of databases onto another instance.

Performance Considerations

  • Edition support. Backup compression is supported on Enterprise, Standard and Developer editions. On any other edition, remove COMPRESSION from the script. The current syntax also accepts an ALGORITHM argument for COMPRESSION (MS_XPRESS or ZSTD); check that your version lists it before using it.
  • Sequential runtime. Databases are backed up one after another, so total time is the sum of all of them. A job that fits a window today can overrun it after one database triples in size. Differential backups can supplement full backups for large databases.
  • One folder, one device. Every file lands on the same volume. A backup can be striped across several files by listing more than one DISK = clause, and each database can point at a different volume if one device is the bottleneck.
  • Existing files are appended to. BACKUP defaults to NOINIT, which appends a new backup set to the file when it already exists. Two runs in the same minute, or a rerun after a fix, write two backup sets into one file. Add INIT to overwrite, or pause until the next minute.
  • No transactions. BACKUP cannot run inside an explicit or implicit transaction. A session with SET IMPLICIT_TRANSACTIONS ON fails on the first backup.
  • Error log noise. Each successful backup adds an entry to the SQL Server error log and the system event log. On an instance with many databases and frequent backups, that crowds out other messages. Trace flag 3226 suppresses those entries, and scripts that read them will stop seeing them.
  • System databases are not covered. master, model and msdb need their own backups. Only a full backup can be taken of master. Run a second pass for those databases on the same schedule.
  • Recovery model. A full backup alone does not protect a database in full recovery. That model requires transaction log backups in addition to data backups.
  • Permissions. BACKUP DATABASE defaults to sysadmin, db_owner and db_backupoperator. The SQL Server service account needs read and write access to the folder, and a permission problem only appears when the backup runs.

Practical Tips

  • Test one database first. Add AND [name] = N'YourDb' to the WHERE clause, run it and confirm that one file with the expected name appears.
  • Exclude databases deliberately. AND [name] NOT IN (N'ScratchDb', N'ReportingStaging') removes ones that do not need a nightly backup.
  • Verify the backup files. After BACKUP DATABASE inside the TRY block, RESTORE VERIFYONLY FROM DISK = @File checks that the backup set is complete and the whole file is readable. It does not check the structure of the data, so it complements a periodic real restore test and does not replace it.
  • Check folder access first. The SQL Server service account needs read and write permission on the folder or share, and a permission problem only appears when the backup runs. Test with one database before scheduling.
  • Schedule it as an Agent job. Use a Transact-SQL step, put the script in it and let the THROW fail the step when any database fails. Add a notification on failure.
  • Clean up separately. The script never deletes old files. Retention belongs in a second job step or a separate script, and it should leave at least the last good backup of every database.
  • Keep a restore test on the calendar. Restore a recent file to a scratch instance regularly to confirm the files can actually be restored.

Conclusion

The script turns the instance's own list of databases into a nightly set of compressed, checksummed full backups, with dated filenames and a job step that fails when any database fails. It does not manage retention, system databases or log backups, so treat it as the full-backup piece of a plan that also covers those.

References

Posts in this series