Backing Up the Database with Code
The BACKUP command offers a few more options than Management Studio, and using the BACKUP
command directly is useful for assembling SQL Server Agent jobs by
hand, rather than with the Maintenance Plan Back Up Database Task.
Without all the options and frills, the most basic BACKUP command is as follows:
BACKUP DATABASE Databasename
TO DISK = ‘file location'
WITH
NAME = ‘backup name';
The following command backs up the AdventureWorks2012 database to a disk file and names the backup AdventureWorks2012Backup:
BACKUP DATABASE AdventureWorks2012
TO DISK = ‘e:\AdventureWorks2012Backup.bak'
WITH
NAME = ‘AdventureWorks2012Backup';
Result:
Processed 17944 pages for database ‘AdventureWorks2012', file
‘AdventureWorks2012_Data' on file 1.
Processed 2 pages for database ‘AdventureWorks2012', file
‘AdventureWorks2012_Log' on file 1.
BACKUP DATABASE successfully processed 17946 pages in 7.954 seconds
(17.625 MB/sec).
The backup command has a few important options that deserve to be mentioned first:
- Backing up to a network share: In the TO DISK
option, you can use a network share as a target. Although this is an
option, you must ensure that the SQL Server service account has proper
rights on the target file share; otherwise you get an access denied
error.
TO DISK = ‘ \\FILESERVER\SQLbackups\AdventureWorks2012Backup.bak'
- Tape (Backup To:): To backup to tape instead of disk, use the TO TAPE option and specify the tape-drive location:
TO TAPE = ‘\\.\TAPE0'
Note
Avoid using the Tape option because this feature will be removed in the future release of SQL Server.
- Differential: Causes the
backup command to perform a differential backup instead of a full
database backup. The following command performs a differential backup:
BACKUP DATABASE AdventureWorks2012
TO DISK = ‘e:\AdventureWorks2012Backup.bak'
WITH
DIFFERENTIAL,
NAME = ‘AdventureWorks2012Backup';
- To back up a file or filegroup, list it after the database name.
This technique can help organize backups. For example, for backup
purposes, you can design your database to place static tables in one
filegroup and active tables in the primary filegroup.
- COMPRESSION/NO_COMPRESSION: Overrides the server-level default backup compression. COMPRESSION enables backup compression and performs checksums to detect media corruptions.
- CHECKSUM/NO_CHECKSUM: Identical to the Perform Checksum Before Writing to Media option within Management Studio.
- STOP_ON_ERROR/CONTINUE_AFTER_ERROR: Identical to Continue on Error option within Management Studio.
The backup command has numerous additional options:
- DESCRIPTION: Identical to the Description field within Management Studio.
- EXPIREDATE: Identical to Management Studio; prevents the backup from being overwritten before the expiration date.
- RETAINDAYS: The number of days, as an integer, before SQL Server overwrites the backup.
- STATS = percentage:
Tells SQL Server to report the progress of the backup in the percentage
increment specified; the default increment is 10 percent. This option
is useful particularly while troubleshooting a failed backup. By using
this option, it gives an idea when the backup is failing. Also, for
huge databases this gives an idea of the percentage of backup completed
and the amount remaining.
- BLOCKSIZE: Sets the physical
block size in bytes. The default is 65536 bytes for tape devices and
512 otherwise. This option is usually not required because backup
automatically selects the correct block size of the device. If a backup
to disk will later be copied to a CD/RW, try a block size of 2048.
- MEDIANAME: Specifies the name
of the media volume. This option serves as a safety check: If the
backup is added to the media, the name must match.
- MEDIADESCRIPTION: Writes an optional media description.
- MediaPassword: Creates an
optional media password that applies to the entire medium (disk file or
tape). The first time the medium is created, the password can be set.
If the password is specified when the medium is created, it must be
specified every subsequent time the backup medium is accessed to add
another backup or to restore.
Note
Avoid using the MediaPassword option because this feature will be removed in the future release of SQL Server.
- INIT/NOINIT: Initializes the
tape or disk file, thus overwriting all existing backup sets in the
medium. SQL Server can prevent initialization if any of the backups in
the medium have not expired or still have the number of retaining days.
NOINIT is the default.
- NOSKIP/SKIP: This option “skips” the backup-name and backup-date checking that normally prevents overwriting backups. NOSKIP is the default.
- NOFORMAT/FORMAT: FORMAT
writes a new media header on media volumes used for backup and
overwrites the existing backup sets; thereby the existing contents of
the volume become unusable. NOFORMAT (default behavior) preserves the existing media header and backup sets. FORMAT automatically includes SKIP and INIT.
The last options apply only when backing up to tape:
- REWIND/NOREWIND: REWIND directs SQL Server to rewind the tape. The default is to REWIND.
- UNLOAD/LOAD: UNLOAD automatically rewinds and unloads the tape. This is the default until the user session specifies load.
- RESTART: This option has no effect. This is there for compatibility with previous versions of SQL Server.
Verifying the Backup with Code
Management Studio's backup includes an option to verify the backup, and the T-SQL Backup command does not. Management Studio actually calls the T-SQL RESTORE VERIFYONLY command after the backup to perform the verification:
RESTORE VERIFYONLY
FROM DISK = ‘e:\AdventureWorks2012Backup.bak'
Result:
The backup set is valid.
The verification has a few options, such as Eject
Tape After Backup. Most of these verification options are for tapes and
are self-explanatory.
Note
RESTORE VERIFYONLY
does not actually restore the database. It checks only if the backup is
complete and is readable. By default it checks the backup checksums if
they are present and proceeds without verification if they are not
present. Although this is a quick way to check if the backup set is
complete and readable, it is not a replacement for actually
performing a restore to see if the backup is valid because this check
does not verify the structure of the data contained in the backup
volumes. The only way to truly test and validate your backups is to
perform a restore.