T-SQL Backup
T-SQL Backup
<backup_device>::=
{
{ logical_device_name | @logical_device_name_var }
| { DISK
| TAPE
| URL } =
{ 'physical_device_name' | @physical_device_name_var | 'NUL' }
}
<MIRROR TO clause>::=
MIRROR TO <backup_device> [ ,...n ]
<file_or_filegroup>::=
{
FILE = { logical_file_name | @logical_file_name_var }
| FILEGROUP = { logical_filegroup_name | @logical_filegroup_name_var }
}
<read_only_filegroup>::=
FILEGROUP = { logical_filegroup_name | @logical_filegroup_name_var }
<general_WITH_options> [ ,...n ]::=
--Backup Set Options
COPY_ONLY
| { COMPRESSION | NO_COMPRESSION }
| DESCRIPTION = { 'text' | @text_variable }
| NAME = { backup_set_name | @backup_set_name_var }
| CREDENTIAL
| ENCRYPTION
| FILE_SNAPSHOT
| { EXPIREDATE = { 'date' | @date_var }
| RETAINDAYS = { days | @days_var } }
--Compatibility Options
RESTART
--Monitoring Options
STATS [ = percentage ]
--Tape Options
{ REWIND | NOREWIND }
| { UNLOAD | NOUNLOAD }
--Log-specific Options
{ NORECOVERY | STANDBY = undo_file_name }
| NO_TRUNCATE
--Encryption Options
ENCRYPTION (ALGORITHM = { AES_128 | AES_192 | AES_256 | TRIPLE_DES_3KEY } ,
encryptor_options ) <encryptor_options> ::=
SERVER CERTIFICATE = Encryptor_Name | SERVER ASYMMETRIC KEY = Encryptor_Name
BACKUP (Transact-SQL)
Backs up a complete SQL Server database to create a database backup, or one or more
files or filegroups of the database to create a file backup (BACKUP DATABASE). Also,
under the full recovery model or bulk-logged recovery model, backs up the transaction
log of the database to create a log backup (BACKUP LOG).
Syntax
SQLCopy
--Backing Up a Whole Database
BACKUPDATABASE { database_name | @database_name_var }
TO<backup_device> [ ,...n ]
[ <MIRROR TO clause> ] [ next-mirror-to ]
[ WITH { DIFFERENTIAL
| <general_WITH_options> [ ,...n ] } ]
[;]
<backup_device>::=
{
{ logical_device_name | @logical_device_name_var }
| { DISK
| TAPE
| URL } =
{ 'physical_device_name' | @physical_device_name_var | 'NUL' }
}
<MIRROR TO clause>::=
MIRROR TO <backup_device> [ ,...n ]
<file_or_filegroup>::=
{
FILE = { logical_file_name | @logical_file_name_var }
| FILEGROUP = { logical_filegroup_name | @logical_filegroup_name_var }
}
<read_only_filegroup>::=
FILEGROUP = { logical_filegroup_name | @logical_filegroup_name_var }
--Monitoring Options
STATS [ = percentage ]
--Tape Options
{ REWIND | NOREWIND }
| { UNLOAD | NOUNLOAD }
--Log-specific Options
{ NORECOVERY | STANDBY = undo_file_name }
| NO_TRUNCATE
--Encryption Options
ENCRYPTION (ALGORITHM = { AES_128 | AES_192 | AES_256 | TRIPLE_DES_3KEY } ,
encryptor_options ) <encryptor_options> ::=
SERVER CERTIFICATE = Encryptor_Name | SERVER ASYMMETRIC KEY = Encryptor_Name
Arguments
DATABASE Specifies a complete database backup. If a list of files and filegroups is
specified, only those files and filegroups are backed up. During a full or differential
database backup, SQL Server backs up enough of the transaction log to produce a
consistent database when the backup is restored.
When you restore a backup created by BACKUP DATABASE (a data backup), the entire
backup is restored. Only a log backup can be restored to a specific time or transaction
within the backup.
Note
LOG
Specifies a backup of the transaction log only. The log is backed up from the last
successfully executed log backup to the current end of the log. Before you can create
the first log backup, you must create a full backup.
You can restore a log backup to a specific time or transaction within the backup by
specifying WITH STOPAT, STOPATMARK, or STOPBEFOREMARK in your RESTORE
LOG statement.
Note
After a typical log backup, some transaction log records become inactive, unless you
specify WITH NO_TRUNCATE or COPY_ONLY. The log is truncated after all the records within
one or more virtual log files become inactive. If the log is not being truncated after
routine log backups, something might be delaying log truncation. For more information,
see Factors that can delay log truncation.
<file_or_filegroup> [ ,...n ] Used only with BACKUP DATABASE, specifies a database file
or filegroup to include in a file backup, or specifies a read-only file or filegroup to
include in a partial backup.
Consider using file backups when the database size and performance requirements
make a database backup impractical. The NUL device can be used to test the
performance of backups, but should not be used in production environments.
n Is a placeholder that indicates that multiple files and filegroups can be specified in a
comma-separated list. The number is unlimited.
For more information, see Full File Backups and Back Up Files and Filegroups.
READ_WRITE_FILEGROUPS [ , FILEGROUP =
{ logical_filegroup_name | @logical_filegroup_name_var } [ ,...n ] ] Specifies a partial
backup. A partial backup includes all the read/write files in a database: the primary
filegroup and any read/write secondary filegroups, and also any specified read-only files
or filegroups.
<backup_device>
Specifies a logical or physical backup device to use for the backup operation.
The NUL disk device will discard all information sent to it and should only be used for
testing. This is not for production use.
Important
Starting with SQL Server 2012 (11.x) SP1 CU2 through SQL Server 2014 (12.x), you can
only backup to a single device when backing up to URL. In order to backup to multiple
devices when backing up to URL, you must use SQL Server 2016 (13.x) through SQL
Server 2017 and you must use Shared Access Signature (SAS) tokens. For examples
creating a Shared Access Signature, see SQL Server Backup to URL and Simplifying
creation of SQL Credentials with Shared Access Signature (SAS) tokens on Azure
Storage with Powershell.
URL applies to: SQL Server ( SQL Server 2012 (11.x) SP1 CU2 through SQL Server 2017).
A disk device does not have to exist before it is specified in a BACKUP statement. If the
physical device exists and the INIT option is not specified in the BACKUP statement, the
backup is appended to the device.
Note
The NUL device will discard all input sent to this file, however the backup will still mark
all pages as backed up.
The TAPE option will be removed in a future version of SQL Server. Avoid using this
feature in new development work, and plan to modify applications that currently use
this feature.
For MIRROR TO = DISK, BACKUP automatically determines the appropriate block size
for disk devices based on the sector size of the disk. If the MIRROR TO disk is formatted
with a different sector size than the disk specified as the primary backup device, the
backup command will fail. In order to mirror backups to devices that have different
sector sizes, the BLOCKSIZE parameter must be specified, and should be set to the
highest sector size amongst all the target devices. For more information about block
size, see "BLOCKSIZE" later in this topic.
CREDENTIAL Applies to: SQL Server ( SQL Server 2012 (11.x) SP1 CU2 through SQL
Server 2017). Used only when creating a backup to the Microsoft Azure Blob storage
service.
FILE_SNAPSHOT Applies to: SQL Server ( SQL Server 2016 (13.x) through SQL Server
2017).
Used to create an Azure snapshot of the database files when all of the SQL Server
database files are stored using the Azure Blob storage service. For more information,
see SQL Server Data Files in Microsoft Azure. SQL Server Snapshot Backup takes Azure
snapshots of the database files (data and log files) at a consistent state. A consistent set
of Azure snapshots make up a backup and are recorded in the backup file. The only
difference between BACKUP DATABASE TO URL WITH FILE_SNAPSHOT and BACKUP LOG TO
URL WITH FILE_SNAPSHOT is that the latter also truncates the transaction log while the
former does not. With SQL Server Snapshot Backup, after the initial full backup that is
required by SQL Server to establish the backup chain, only a single transaction log
backup is required to restore a database to the point in time of the transaction log
backup. Furthermore, only two transaction log backups are required to restore a
database to a point in time between the time of the two transaction log backups.
DIFFERENTIAL
Used only with BACKUP DATABASE, specifies that the database or file backup should
consist only of the portions of the database or file changed since the last full backup. A
differential backup usually takes up less space than a full backup. Use this option so that
all individual log backups performed since the last full backup do not have to be
applied.
Note
ENCRYPTION Used to specify encryption for a backup. You can specify an encryption
algorithm to encrypt the backup with or specify NO_ENCRYPTION to not have the backup
encrypted. Encryption is recommended practice to help secure backup files. The list of
algorithms you can specify are:
AES_128
AES_192
AES_256
TRIPLE_DES_3KEY
NO_ENCRYPTION
If you choose to encrypt you will also have to specify the encryptor using the encryptor
options:
Warning
When encryption is used in conjunction with the FILE_SNAPSHOT argument, the metadata
file itself is encrypted using the specified encryption algorithm and the system verifies
that Transparent Data Encryption (TDE) was completed for the database. No
additional encryption happens for the data itself. The backup fails if the database was
not encrypted or if the encryption was not completed before the backup statement was
issued.
These options operate on the backup set that is created by this backup operation.
Note
COPY_ONLY Specifies that the backup is a copy-only backup, which does not affect the
normal sequence of backups. A copy-only backup is created independently of your
regularly scheduled, conventional backups. A copy-only backup does not affect your
overall backup and restore procedures for the database.
Copy-only backups should be used in situations in which a backup is taken for a special
purpose, such as backing up the log before an online file restore. Typically, a copy-only
log backup is used once and then deleted.
When used with BACKUP DATABASE, the COPY_ONLY option creates a full backup that
cannot serve as a differential base. The differential bitmap is not updated, and
differential backups behave as if the copy-only backup does not exist. Subsequent
differential backups use the most recent conventional full backup as their base.
Important
When used with BACKUP LOG, the COPY_ONLY option creates a copy-only log backup,
which does not truncate the transaction log. The copy-only log backup has no
effect on the log chain, and other log backups behave as if the copy-only backup
does not exist.
At installation, the default behavior is no backup compression. But this default can be
changed by setting the backup compression default server configuration option. For
information about viewing the current value of this option, see View or Change Server
Properties.
For information about using backup compression with Transparent Data Encryption
(TDE) enabled databases, see the Remarks section.
{ EXPIREDATE ='date' | RETAINDAYS = days } Specifies when the backup set for this
backup can be overwritten. If these options are both used, RETAINDAYS takes
precedence over EXPIREDATE.
These options only prevent SQL Server from overwriting a file. Tapes can be erased
using other methods, and disk files can be deleted through the operating system. For
more information about expiration verification, see SKIP and FORMAT in this topic.
EXPIREDATE = { 'date' | @date_var } Specifies when the backup set expires and can be
overwritten. If supplied as a variable (@date_var), this date must follow the configured
system datetime format and be specified as one of the following:
For example:
For information about how to specify datetime values, see Date and Time Types.
Note
RETAINDAYS = { days | @days_var } Specifies the number of days that must elapse
before this backup media set can be overwritten. If supplied as a variable (@days_var), it
must be specified as an integer.
{ NOINIT | INIT } Controls whether the backup operation appends to or overwrites the
existing backup sets on the backup media. The default is to append to the most recent
backup set on the media (NOINIT).
Note
For information about the interactions between { NOINIT | INIT } and { NOSKIP | SKIP },
see Remarks later in this topic.
NOINIT Indicates that the backup set is appended to the specified media set, preserving
existing backup sets. If a media password is defined for the media set, the password
must be supplied. NOINIT is the default.
For more information, see Media Sets, Media Families, and Backup Sets.
INIT Specifies that all backup sets should be overwritten, but preserves the media
header. If INIT is specified, any existing backup set on that device is overwritten, if
conditions permit. By default, BACKUP checks for the following conditions and does not
overwrite the backup media if either condition exists:
Any backup set has not yet expired. For more information, see
the EXPIREDATE and RETAINDAYS options.
The backup set name given in the BACKUP statement, if provided, does not match
the name on the backup media. For more information, see the NAME option,
earlier in this section.
For more information, see Media Sets, Media Families, and Backup Sets.
{ NOSKIP | SKIP } Controls whether a backup operation checks the expiration date and
time of the backup sets on the media before overwriting them.
Note
For information about the interactions between { NOINIT | INIT } and { NOSKIP | SKIP },
see "Remarks," later in this topic.
NOSKIP Instructs the BACKUP statement to check the expiration date of all backup sets
on the media before allowing them to be overwritten. This is the default behavior.
SKIP Disables the checking of backup set expiration and name that is usually performed
by the BACKUP statement to prevent overwrites of backup sets. For information about
the interactions between { INIT | NOINIT } and { NOSKIP | SKIP }, see "Remarks," later in
this topic. To view the expiration dates of backup sets, query
the expiration_date column of the backupset history table.
{ NOFORMAT | FORMAT } Specifies whether the media header should be written on the
volumes used for this backup operation, overwriting any existing media header and
backup sets.
NOFORMAT Specifies that the backup operation preserves the existing media header
and backup sets on the media volumes used for this backup operation. This is the
default behavior.
FORMAT Specifies that a new media set be created. FORMAT causes the backup
operation to write a new media header on all media volumes used for the backup
operation. The existing contents of the volume become invalid, because any existing
media header and backup sets are overwritten.
Important
Use FORMAT carefully. Formatting any volume of a media set renders the entire media set
unusable. For example, if you initialize a single tape belonging to an existing striped
media set, the entire media set is rendered useless.
Specifying FORMAT implies SKIP; SKIP does not need to be explicitly stated.
If you are taking a backup that you plan to copy onto and restore from a CD-ROM,
specify BLOCKSIZE=2048.
Note
This option typically affects performance only when writing to tape devices.
For important information about using the BUFFERCOUNT option, see the Incorrect
BufferCount data transfer option can lead to OOM condition blog.
For Transparent Data Encryption (TDE) enabled databases with a single data file, the
default MAXTRANSFERSIZE is 65536 (64 KB). For non-TDE encrypted databases the
default MAXTRANSFERSIZE is 1048576 (1 MB) when using backup to DISK, and 65536 (64
KB) when using VDI or TAPE. For more information about using backup compression
with TDE encrypted databases, see the Remarks section.
These options allow you to determine whether backup checksums are enabled for the
backup operation and whether the operation stops on encountering an error.
CHECKSUM Specifies that the backup operation verifies each page for checksum and
torn page, if enabled and available, and generate a checksum for the entire backup.
For more information, see Possible Media Errors During Backup and Restore.
STOP_ON_ERROR Instructs BACKUP to fail if a page checksum does not verify. This is the
default behavior.
If you are unable to back up the tail of the log using the NO_TRUNCATE option when
the database is damaged, you can attempt a tail-log log backup by specifying
CONTINUE_AFTER_ERROR instead of NO_TRUNCATE.
For more information, see Possible Media Errors During Backup and Restore.
Compatibility Options
RESTART Beginning with SQL Server 2008, has no effect. This option is accepted by the
version for compatibility with previous versions of SQL Server.
Monitoring Options
The STATS option reports the percentage complete as of the threshold for reporting the
next interval. This is at approximately the specified percentage; for example, with
STATS=10, if the amount completed is 40 percent, the option might display 43 percent.
For large backup sets, this is not a problem, because the percentage complete moves
very slowly between completed I/O calls.
Tape Options
These options are used only for TAPE devices. If a nontape device is being used, these
options are ignored.
Specifies that SQL Server releases and rewinds the tape. REWIND is the default.
NOREWIND
Specifies that SQL Server will keep the tape open after the backup operation. You can
use this option to help improve performance when performing multiple backup
operations to a tape.
NOREWIND implies NOUNLOAD, and these options are incompatible within a single
BACKUP statement.
Note
If you use NOREWIND, the instance of SQL Server retains ownership of the tape drive until
a BACKUP or RESTORE statement that is running in the same process uses either
the REWIND or UNLOAD option, or the server instance is shut down. Keeping the tape open
prevents other processes from accessing the tape. For information about how to display
a list of open tapes and to close an open tape, see Backup Devices.
{ UNLOAD | NOUNLOAD }
Note
UNLOAD and NOUNLOAD are session settings that persist for the life of the session or until it
is reset by specifying the alternative.
UNLOAD
Specifies that the tape is automatically rewound and unloaded when the backup is
finished. UNLOAD is the default when a session begins.
NOUNLOAD
Specifies that after the BACKUP operation the tape remains loaded on the tape drive.
Note
For a backup to a tape backup device, the BLOCKSIZE option to affect the performance
of the backup operation. This option typically affects performance only when writing to
tape devices.
Log-specific options
If you do not want to take log backups, use the simple recovery model. For more
information, see Recovery Models.
NORECOVERY
Backs up the tail of the log and leaves the database in the RESTORING state.
NORECOVERY is useful when failing over to a secondary database or when saving the
tail of the log before a RESTORE operation.
To perform a best-effort log backup that skips log truncation and then take the
database into the RESTORING state atomically, use
the NO_TRUNCATE and NORECOVERY options together.
STANDBY = standby_file_name
Backs up the tail of the log and leaves the database in a read-only and STANDBY state.
The STANDBY clause writes standby data (performing rollback, but with the option of
further restores). Using the STANDBY option is equivalent to BACKUP LOG WITH
NORECOVERY followed by a RESTORE WITH STANDBY.
This file holds the rolled back changes, which must be reversed if RESTORE LOG
operations are to be subsequently applied. There must be enough disk space for the
standby file to grow so that it can contain all the distinct pages from the database that
were modified by rolling back uncommitted transactions.
NO_TRUNCATE
Specifies that the is log not truncated and causes the Database Engine to attempt the
backup regardless of the state of the database. Consequently, a backup taken
with NO_TRUNCATE might have incomplete metadata. This option allows backing up the
log in situations where the database is damaged.
Without the NO_TRUNCATE option, the database must be in the ONLINE state. If the
database is in the SUSPENDED state, you might be able to create a backup by
specifying NO_TRUNCATE. But if the database is in the OFFLINE or EMERGENCY state,
BACKUP is not allowed even with NO_TRUNCATE. For information about database states,
see Database States.
About working with SQL Server backups
This section introduces the following essential backup concepts:
Backup Types Transaction Log Truncation Formatting Backup Media Working with
Backup Devices and Media Sets Restoring SQL Server Backups
Note
The supported backup types depend on the recovery model of the database, as follows
Partial Partial backups cover read/-write filegroups and, possibly, one or more read-only files or
database filegroups.
Optionally, each partial backup can serve as the base of a series of one or more differential
partial backups.
File or File backups cover one or more files or filegroups, and are relevant only for databases that
filegroup contain multiple filegroups. Under the simple recovery model, file backups are essentially
restricted to read-only secondary filegroups.
Optionally, each file backup can serve as the base of a series of one or more differential file
backups.
We recommend that you put log backups on a separate volume than the database
backups.
Note
Before you can create the first log backup, you must create a full backup.
A copy-only backup is a special-purpose full backup or log backup that is
independent of the normal sequence of conventional backups. To create a copy-
only backup, specify the COPY_ONLY option in your BACKUP statement. For more
information, see Copy-Only Backups.
Transaction Log Truncation
To avoid filling up the transaction log of a database, routine backups are essential.
Under the simple recovery model, log truncation occurs automatically after you back up
the database, and under the full recovery model, after you back up the transaction log.
However, sometimes the truncation process can be delayed. For information about
factors that can delay log truncation, see The Transaction Log.
Note
The BACKUP LOG WITH NO_LOG and WITH TRUNCATE_ONLY options have been discontinued.
If you are using the full or bulk-logged recovery model recovery and you must remove
the log backup chain from a database, switch to the simple recovery model. For more
information, see View or Change the Recovery Model of a Database.
Formatting Backup Media
Backup media is formatted by a BACKUP statement if and only if any of the following is
true:
A stripe set is a set of disk files on which data is divided into blocks and distributed in a
fixed order. The number of backup devices used in a stripe set must stay the same
(unless the media is reinitialized with FORMAT).
After a backup device is defined as part of a stripe set, it cannot be used for a single-
device backup unless FORMAT is specified. Similarly, a backup device that contains
nonstriped backups cannot be used in a stripe set unless FORMAT is specified. To split a
striped backup set, use FORMAT.
Typically, backups are unmirrored, and BACKUP statements simply include a TO clause.
However, a total of four mirrors is possible per media set. For a mirrored media set, the
backup operation writes to multiple groups of backup devices. Each group of backup
devices comprises a single mirror within the mirrored media set. Every mirror must use
the same quantity and type of physical backup devices, which must all have the same
properties.
To back up to a mirrored media set, all of the mirrors must be present. To back up to a
mirrored media set, specify the TO clause to specify the first mirror, and specify a MIRROR
TO clause for each additional mirror.
For a mirrored media set, each MIRROR TO clause must list the same number and type of
devices as the TO clause. The following example writes to a mirrored media set that
contains two mirrors and uses three devices per mirror:
SQLCopy
BACKUPDATABASE AdventureWorks2012
TO DISK='X:\SQLServerBackups\AdventureWorks1a.bak',
DISK='Y:\SQLServerBackups\AdventureWorks2a.bak',
DISK='Z:\SQLServerBackups\AdventureWorks3a.bak'
MIRROR TO DISK='X:\SQLServerBackups\AdventureWorks1b.bak',
DISK='Y:\SQLServerBackups\AdventureWorks2b.bak',
DISK='Z:\SQLServerBackups\AdventureWorks3b.bak';
GO
Important
This example is designed to allow you to test it on your local system. In practice, backing
up to multiple devices on the same drive would hurt performance and would eliminate
the redundancy for which mirrored media sets are designed.
Media families in mirrored media sets
Each backup device specified in the TO clause of a BACKUP statement corresponds to a
media family. For example, if the TO clauses lists three devices, BACKUP writes data to
three media families. In a mirrored media set, every mirror must contain a copy of every
media family. This is why the number of devices must be identical in every mirror.
When multiple devices are listed for each mirror, the order of the devices determines
which media family is written to a particular device. For example, in each of the device
lists, the second device corresponds to the second media family. For the devices in the
above example, the correspondence between devices and media families is shown in the
following table.
Mirror Media family 1 Media family 2 Media family 3
A media family must always be backed up onto the same device within a specific mirror.
Therefore, each time you use an existing media set, list the devices of each mirror in the
same order as they were specified when the media set was created.
For more information about mirrored media sets, see Mirrored Backup Media Sets. For
more information about media sets and media families in general, see Media Sets,
Media Families, and Backup Sets.
Restoring SQL Server backups
This table describes interactions between the { NOINIT | INIT } and { NOSKIP | SKIP }
options.
Note
If the tape media is empty or the disk backup file does not exist, all these interactions
write a media header and proceed. If the media is not empty and lacks a valid media
header, these operations give feedback stating that this is not valid MTF media, and
NOINIT INIT
NOSKI If the volume contains a valid If the volume contains a valid media header,
P media header, verifies that the performs the following checks:
media name matches the
given MEDIANAME, if any. If it
matches, appends the backup If MEDIANAME was specified, verifies that the
set, preserving all existing given media name matches the media header's
backup sets. media name. 1
If the volume does not contain a Verifies that there are no unexpired backup sets
valid media header, an error already on the media. If there are, terminates
occurs. the backup.
SKIP If the volume contains a valid If the volume contains a valid media header,
2
media header, appends the overwrites any backup sets on the media, preserving
backup set, preserving all only the media header.
existing backup sets. If the media is empty, generates a media header using
the specified MEDIANAME and MEDIADESCRIPTION, if
any.
1
The user must belong to the appropriate fixed database or server roles to perform a
backup operation.
2
Validity includes the MTF version number and other header information. If the version
specified is unsupported or an unexpected value, an error occurs.
Compatibility
Caution
Backups that are created by more recent version of SQL Server cannot be restored in
earlier versions of SQL Server.
BACKUP supports the RESTART option to provide backward compatibility with earlier
versions of SQL Server. But RESTART has no effect.
General remarks
Database or log backups can be appended to any disk or tape device, allowing a
database and its transaction logs to be kept within one physical location.
When using backup compression with Transparent Data Encryption (TDE) enabled
databases with a single data file, it is recommended to use
a MAXTRANSFERSIZE setting larger than 65536 (64 KB). Starting with SQL Server 2016
(13.x), this enables an optimized compression algorithm for TDE encrypted databases
that first decrypts a page, compresses it and then encrypts it again. If
using MAXTRANSFERSIZE = 65536 (64 KB), backup compression with TDE encrypted
databases directly compresses the encrypted pages, and may not yield good
compression ratios. For more information, see Backup Compression for TDE-enabled
Databases.
Note
There are some cases where the default MAXTRANSFERSIZE is greater than 64K:
When the database has multiple data files created, it uses MAXTRANSFERSIZE > 64K
When performing backup to URL, the default MAXTRANSFERSIZE = 1048576 (1MB)
Even if one of these conditions applies, you must explicitly set MAXTRANSFERSIZE greater
than 64K in your backup command in order to get the new backup compression
algorithm.
By default, every successful backup operation adds an entry in the SQL Server error log
and in the system event log. If back up the log very frequently, these success messages
accumulate quickly, resulting in huge error logs that can make finding other messages
difficult. In such cases you can suppress these log entries by using trace flag 3226 if
none of your scripts depend on those entries. For more information, see Trace Flags.
Interoperability
SQL Server uses an online backup process to allow a database backup while the
database is still in use. During a backup, most operations are possible; for example,
INSERT, UPDATE, or DELETE statements are allowed during a backup operation.
Operations that cannot run during a database or transaction log backup include:
File management operations such as the ALTER DATABASE statement with either
the ADD FILE or REMOVE FILE options.
Shrink database or shrink file operations. This includes auto-shrink operations.
backupfile
backupfilegroup
backupmediafamily
backupmediaset
backupset
When a restore is performed, if the backup set was not already recorded in
the msdb database, the backup history tables might be modified.
Security
Beginning with SQL Server 2012 (11.x), the PASSWORD and MEDIAPASSWORD options are
discontinued for creating backups. It is still possible to restore backups created with
passwords.
Permissions
Ownership and permission problems on the backup device's physical file can interfere
with a backup operation. SQL Server must be able to read and write to the device; the
account under which the SQL Server service runs must have write permissions.
However, sp_addumpdevice, which adds an entry for a backup device in the system
tables, does not check file access permissions. Such problems on the backup device's
physical file may not appear until the physical resource is accessed when the backup or
restore is attempted.
Examples
This section contains the following examples:
Note
The backup how-to topics contain additional examples. For more information,
see Backup Overview.
A. Backing up a complete database
Next, the example uses sp_addumpdevice to create a logical backup device for backing
up data, AdvWorksData, and creates another logical backup device for backing up the
log, AdvWorksLog.
The example then creates a full database backup to AdvWorksData, and after a period of
update activity, backs up the log to AdvWorksLog.
SQLCopy
-- To permit log backups, before the full database backup, modify the database
-- to use the full recovery model.
USEmaster;
GO
ALTERDATABASE AdventureWorks2012
SETRECOVERYFULL;
GO
-- Create AdvWorksData and AdvWorksLog logical backup devices.
USEmaster
GO
EXEC sp_addumpdevice 'disk', 'AdvWorksData',
'Z:\SQLServerBackups\AdvWorksData.bak';
GO
EXEC sp_addumpdevice 'disk', 'AdvWorksLog',
'X:\SQLServerBackups\AdvWorksLog.bak';
GO
For a production database, back up the log regularly. Log backups should be frequent
enough to provide sufficient protection against data loss.
C. Creating a full file backup of the secondary filegroups
The following example creates a full file backup of every file in both of the secondary
filegroups.
SQLCopy
--Back up the files in SalesGroup1:
BACKUPDATABASE Sales
FILEGROUP = 'SalesGroup1',
FILEGROUP = 'SalesGroup2'
TO DISK = 'Z:\SQLServerBackups\SalesFiles.bck';
GO
D. Creating a differential file backup of the secondary filegroups
The following example creates a differential file backup of every file in both of the
secondary filegroups.
SQLCopy
--Back up the files in SalesGroup1:
BACKUPDATABASE Sales
FILEGROUP = 'SalesGroup1',
FILEGROUP = 'SalesGroup2'
TO DISK = 'Z:\SQLServerBackups\SalesFiles.bck'
WITH
DIFFERENTIAL;
GO
E. Creating and backing up to a single-family mirrored media set
The following example creates a mirrored media set containing a single media family
and four mirrors and backs up the AdventureWorks2012 database to them.
SQLCopy
BACKUPDATABASE AdventureWorks2012
TO TAPE = '\\.\tape0'
MIRROR TO TAPE = '\\.\tape1'
MIRROR TO TAPE = '\\.\tape2'
MIRROR TO TAPE = '\\.\tape3'
WITH
FORMAT,
MEDIANAME = 'AdventureWorksSet0';
F. Creating and backing up to a multifamily mirrored media set
The following example creates a mirrored media set in which each mirror consists of two
media families. The example then backs up the AdventureWorks2012 database to both
mirrors.
SQLCopy
BACKUPDATABASE AdventureWorks2012
TO TAPE = '\\.\tape0', TAPE = '\\.\tape1'
MIRROR TO TAPE = '\\.\tape2', TAPE = '\\.\tape3'
WITH
FORMAT,
MEDIANAME = 'AdventureWorksSet1';
G. Backing up to an existing mirrored media set
The following example appends a backup set to the media set created in the preceding
example.
SQLCopy
BACKUPLOG AdventureWorks2012
TO TAPE = '\\.\tape0', TAPE = '\\.\tape1'
MIRROR TO TAPE = '\\.\tape2', TAPE = '\\.\tape3'
WITH
NOINIT,
MEDIANAME = 'AdventureWorksSet1';
Note
The following example formats the media, creating a new media set, and perform a
compressed full backup of the AdventureWorks2012 database.
SQLCopy
BACKUPDATABASE AdventureWorks2012 TO DISK='Z:\SQLServerBackups\
AdvWorksData.bak'
WITH
FORMAT,
COMPRESSION;
I. Backing up to the Microsoft Azure Blob storage service
The example performs a full database backup of Sales to the Microsoft Azure Blob
storage service. The storage Account name is mystorageaccount. The container is
called myfirstcontainer. A stored access policy has been created with read, write,
delete, and list rights. The SQL Server
credential, https://mystorageaccount.blob.core.windows.net/myfirstcontainer, was
created using a Shared Access Signature that is associated with the Stored Access Policy.
For information on SQL Server backup to the Microsoft Azure Blob storage service,
see SQL Server Backup and Restore with Microsoft Azure Blob Storage Service and SQL
Server Backup to URL.
SQLCopy
BACKUPDATABASE Sales
TOURL =
'https://mystorageaccount.blob.core.windows.net/myfirstcontainer/Sales_2016072
6.bak'
WITH STATS = 5;
media set
An ordered collection of backup media, tapes or disk files, that uses a fixed type and
number of backup devices. For more information about media sets, see Media Sets,
Media Families, and Backup Sets (SQL Server).
SQL Server Backups can also be written to Windows Azure Blob storage service in
addition to disk or tape.
Using disk backup devices
If a disk file fills while a backup operation is appending a backup to the media set, the
backup operation fails. The maximum size of a backup file is determined by the free disk
space available on the disk device; therefore, the appropriate size for a backup disk
device depends on the size of your backups.
A disk backup device could be a simple disk device, such as an ATA drive. Alternatively,
you could use a hot-swappable disk drive that would let you transparently replace a full
disk on the drive with an empty disk. A backup disk can be a local disk on the server or a
remote disk that is a shared network resource. For information about how to use a
remote disk, see Backing Up to a File on a Network Share, later in this topic.
SQL Server management tools are very flexible at handling disk backup devices because
they automatically generate a time-stamped name on the disk file.
IMPORTANT! We recommend that a backup disk be a different disk than the database
data and log disks. This is necessary to make sure that you can access the backups if the
data or log disk fails.
If database files and backup files are on the same device and the device fails, the
database and backups will be unavailable. Also, putting the database and backup files
on the separate devices optimizes the I/O performance for both the production use of
the database and the writing of backups.
Specify a backup file using its physical name (Transact-
SQL)
The basic BACKUP syntax for specifying a backup file by using its physical device name
is:
For example:
SQLCopy
BACKUPDATABASE AdventureWorks2012
TO DISK = 'Z:\SQLServerBackups\AdventureWorks2012.bak';
GO
To specify a physical disk device in a RESTORE statement, the basic syntax is:
For example,
SQLCopy
RESTOREDATABASE AdventureWorks2012
FROM DISK = 'Z:\SQLServerBackups\AdventureWorks2012.bak';
To avoid ambiguity, especially in scripts, we recommend that you explicitly specify the
path of the backup directory in every DISK clause. However, this is less important when
you are using Query Editor. In that case, if you are sure that the backup file resides in
the default backup directory, you can omit the path from a DISK clause. For example,
the following BACKUP statement backs up the AdventureWorks2012 database to the
default backup directory.
SQLCopy
BACKUPDATABASE AdventureWorks2012
TO DISK = 'AdventureWorks2012.bak';
GO
For SQL Server to access a remote disk file, the SQL Server service account must have
access to the network share. This includes having the permissions needed for backup
operations to write to the network share and for restore operations to read from it. The
availability of network drives and permissions depends on the context is which SQL
Server service is running:
When you run Sqlservr.exe as a service, SQL Server runs in a separate session that
has no relation to your login session. The session in which a service runs can have
its own mapped drives, although it usually does not.
You can connect with the network service account by using the computer account
instead of a domain user. To enable backups from specific computers to a shared
drive, grant access to the computer accounts. As long as the Sqlservr.exe process
that is writing the backup has access, it is irrelevant whether the user sending the
BACKUP command has access.
IMPORTANT! Backing up data over a network can be subject to network errors;
therefore, we recommend that when you are using a remote disk you verify the
backup operation after it finishes. For more information, see RESTORE VERIFYONLY
(Transact-SQL).
Specify a Universal Naming Convention (UNC) name
To specify a network share in a backup or restore command, use the fully qualified
universal naming convention (UNC) name of the file for the backup device. A UNC name
has the form \\Systemname\ShareName\Path\FileName.
For example:
SQLCopy
BACKUPDATABASE AdventureWorks2012
TO DISK = '\\BackupSystem\BackupDisk1\AW_backups\AdventureWorksData.Bak';
GO
Backing up SQL Server data to tape requires that the tape drive or drives be supported
by the Microsoft Windows operating system. Additionally, for the given tape drive, we
recommend that you use only tapes recommended by the drive manufacturer. For more
information about how to install a tape drive, see the documentation for the Windows
operating system.
When a tape drive is used, a backup operation may fill one tape and continue onto
another tape. Each tape contains a media header. The first media used is called
the initial tape. Each successive tape is known as a continuation tape and has a media
sequence number that is one higher than the previous tape. For example, a media set
associated with four tape devices contains at least four initial tapes (and, if the database
does not fit, four series of continuation tapes). When appending a backup set, you must
mount the last tape in the series. If the last tape is not mounted, the Database Engine
scans forward to the end of the mounted tape and then requires that you change the
tape. At that point, mount the last tape.
Tape backup devices are used like disk devices, with the following exceptions:
The tape device must be connected physically to the computer that is running an
instance of SQL Server. Backing up to remote tape devices is not supported.
If a tape backup device is filled during the backup operation, but more data still
must be written, SQL Server prompts for a new tape and continues the backup
operation after a new tape is loaded.
Specify a backup tape using its physical name
(Transact-SQL)
The basic BACKUP syntax for specifying a backup tape using the physical device name of
the tape drive is:
For example:
SQLCopy
BACKUPLOG AdventureWorks2012
TO TAPE = '\\.\tape0';
GO
To specify a physical tape device in a RESTORE statement, the basic syntax is:
To facilitate tape management, the BACKUP statement provides the following tape-
specific options:
{ NOUNLOAD | UNLOAD }
You can control whether a backup tape is unloaded automatically from the tape
drive after a backup or restore operation. UNLOAD/NOUNLOAD is a session
setting that persists for the life of the session or until it is reset by specifying the
alternative.
{ REWIND | NOREWIND }
You can control whether SQL Server keeps the tape remains open after the backup
or restore operation or releases and rewinds the tape after it fills. The default
behavior is to rewind the tape (REWIND).
NOTE: For more information about the BACKUP syntax and arguments, see BACKUP
(Transact-SQL). For more information about the RESTORE syntax and arguments,
see RESTORE (Transact-SQL) and RESTORE Arguments (Transact-SQL), respectively.
Managing open tapes
To view a list of open tape devices and the status of mount requests, query
the sys.dm_io_backup_tapes dynamic management view. This view shows all the open
tapes. These include in-use tapes that are temporarily idle while they wait for the next
BACKUP or RESTORE operation.
If a tape has been accidentally left open, the fastest way to release the tape is by using
the following command: RESTORE REWINDONLY FROM TAPE =backup_device_name.
For more information, see RESTORE REWINDONLY (Transact-SQL).
Using the Windows Azure Blob Storage service
SQL Server Backups can be written to the Windows Azure Blob Storage Service. For
more information on how to use the Windows Azure Blob storage service for your
backups, see SQL Server Backup and Restore with Microsoft Azure Blob Storage Service.
Use a logical backup device
A logical backup device is an optional, user-defined name that points to a specific
physical backup device (a disk file or tape drive). A logical backup device lets you use
indirection when referencing the corresponding physical backup device.
Defining a logical backup device involves assigning a logical name to a physical device.
For example, a logical device, AdventureWorksBackups, could be defined to point to the
Z:\SQLServerBackups\AdventureWorks2012.bak file or the \\.\tape0 tape drive. Backup
and restore commands can then specify AdventureWorksBackups as the backup device,
instead of DISK = 'Z:\SQLServerBackups\AdventureWorks2012.bak' or TAPE = '\\.\tape0'.
The logical device name must be unique among all the logical backup devices on the
server instance. To view the existing logical device names, query
the sys.backup_devices catalog view. This view displays the name of each logical backup
device and describes the type and physical file name or path of the corresponding
physical backup device.
After a logical backup device is defined, in a BACKUP or RESTORE command, you can
specify the logical backup device instead of the physical name of the device. For
example, the following statement backs up the AdventureWorks2012 database to
the AdventureWorksBackups logical backup device.
SQLCopy
BACKUPDATABASE AdventureWorks2012
TO AdventureWorksBackups;
GO
NOTE: In a given BACKUP or RESTORE statement, the logical backup device name and
the corresponding physical backup device name are interchangeable.
One advantage of using a logical backup device is that it is simpler to use than a long
path. Using a logical backup device can help if you plan to write a series of backups to
the same path or to a tape device. Logical backup devices are especially useful for
identifying tape backup devices.
A backup script can be written to use a particular logical backup device. This lets you
switch to a new physical backup devices without updating the script. Switching involves
the following process:
2. Defining a new logical backup device that uses the original logical device name but
maps to a different physical backup device. Logical backup devices are especially
useful for identifying tape backup devices.
Mirrored backup media sets
Mirroring of backup media sets reduces the effect of backup-device malfunctions. These
malfunctions are especially serious because backups are the last line of defense against
data loss. As the sizes of databases grow, the probability increases that a failure of a
backup device or media will make a backup nonrestorable. Mirroring backup media
increases the reliability of backups by providing redundancy for the physical backup
device. For more information, see Mirrored Backup Media Sets (SQL Server).
NOTE: Mirrored backup media sets are supported only in SQL Server 2005 Enterprise
Edition and later versions.
Archive SQL Server backups
We recommend that you use a file system backup utility to archive the disk backups and
that you store the archives off-site. Using disk has the advantage that you use the
network to write the archived backups onto an off-site disk. The Windows Azure Blob
storage service can be used as off-site archival option. You can either upload your disk
backups, or directly write the backups to the Windows Azure Blob storage service.
Another common archiving approach is to write SQL Server backups onto a local backup disk,
archive them to tape, and then store the tapes off-site.
3. Upload the backup to a remote destination – network, NAS, FTP on one of the cloud
storages (Dropbox, AWS, OneDrive, SkyDrive, etc..)
SQLBackupAndFTP
Microsoft SQL Server Management Studio & SQL Server Agent
T-SQL
Ola Hallengren script
or you can just jump straight to the Conclusion
Do not overlook how difficult it is to restore. We’ve included short references on how to
do it for every tool below. For more details read How to restore SQL Server backup.
Note also, that you don’t have to backup the whole database, especially if it’s quite big.
You can backup only those changes that had place since the previous backup. For
more information read about Full vs Differential backups.
1. First download, install it, run and connect to your SQL Server. Then select the databases to
backup.
3. To create a backup schedule turn on “Schedule backups” and set the time to backup for
simple full daily backups. Or click the gear button to open “Advanced backup schedule” for
Differential and Transaction log backup and other options.
4. Compression is set by default and you can set encryption if you want to
5. Press “Run Now” to test the whole job. Then just the program – the job will run on schedule.
6. If you need to restore on the same computer – just select one of the backups from the
“History & restore” section, click on the 3-dot icon and click “Restore”:
To restore on a different computer, install SQLBackupAndFTP there, select “Restore” in
the menu and use the interface to select the backup to restore from.
Or you can just download the backup through SQLBackupAndFTP, a file manager or
the cloud destination client, unzip the file and use the standard RESTORE DATABASE
command.
2. In Object Explorer, connect to an instance of the SQL Server Database Engine and then
expand that instance
3. Expand Databases and then right-click one of the databases you want to backup
8. In the Compression section, use the Set backup compression drop-down list to select
the desired compression level.
9. In the Encryption section, use the Encrypt backup checkbox to decide whether to use
encryption for the backup.
5. Press OK and if everything is OK you will see a notification that a backup of selected
database is finished
1. In the Object Explorer panel, under the SQL Server Agent node, right
click Jobs and select New job from the context menu
2. In the New Job dialog enter a job’s name
3. Under the Steps tab click on the New button and create a backup step by inserting a T-
SQL statement. In this case the CHECKSUM clause has to be included in T-SQL code.
4. Click ok to add a step, and click OK to create a job
5. To schedule a job, in the New Job dialog, under the Schedule tab click New.
6. In the Job Schedule select an occurring frequency, duration and a start date and click
OK:
7. To check a created job in the Object Explorer pane and under the SQL Server Agent ➜
Jobs node right click the job create above and select the Start job at step option:
You can find even more detailed explanations on backups with SSMS in this article.
USE MyDatabase;
GO
BACKUP DATABASE MyDatabase
TO DISK = 'C:SQLServerBackupsMyDatabase.Bak'
WITH FORMAT,
MEDIANAME = 'C_SQLServerBackups',
NAME = 'Full Backup of MyDatabase;
GO
To schedule the backups using Transact-SQL and Windows Task Scheduler follow
these steps (from original article):
1.
1. Use SQL Server Management Studio or Sqlcmd to create the following stored procedure
in your master database:
2. USE [master]
3. GO
4. SET ANSI_NULLS ON
5. GO
6. SET QUOTED_IDENTIFIER ON
7. GO
12. AS
17. )
18.
21.
28.
31.
34.
35. -- Create backup filename in pathfilename.extension format for
full,diff and log backups
37.
40.
43.
EXEC(@sqlCommand)
45. In a text editor, create a batch file that is named Sqlbackup.bat, and then copy the text
from the following example into that file:
46. Schedule a job by using Windows Task Scheduler to execute the batch file that you
created in step 2. To do this, follow these steps:
1. On the computer that is running SQL Server Express, click Start, point to All
Programs, point to Accessories, point to System Tools, and then click Scheduled
Tasks.
2. Double-click Add Scheduled Task.
3. In the Scheduled Task Wizard, click Next.
4. Click Browse, click the batch file that you created in step B, and then click Open.
5. Type SQLBACKUP for the name of the task, click Daily, and then click Next.
6. Specify information for a schedule to run the task. (We recommend that you run this
task at least one time every day.) Then, click Next.
7. In the Enter the user name field, type a user name, and then type a password in
the Enter the password field.
8. Click Next, and then click Finish.
9. Execute the scheduled task at least one time to make sure that the backup is created
successfully.
Ola Hallengren has developed a series of stored procedures which together provide a
maintenance solution with the additional flexibility and features required to manage your
databases.
Getting started with the SQL Server Maintenance Solution is easy. Follow these steps.
1. Download MaintenanceSolution.sql.
2. Open that script in SQL Server Management Studio
and replace NULL with your cleanup time. The cleanup time is the number of hours
after which the backup files are deleted.
5. Execute MaintenanceSolution.sql.
You could find more details on Ola’s site.
Conclusion
There are a number of ways to automate SQL Server backups.
SQLBackupAndFTP is by far the simplest and includes built-in encryption and a variety
of destinations, so that you can more easily integrate it with the services you currently
use. Additionally, its’ basic plan is free.
Traditional SSMS method is cumbersome, does not work in SQL Server Express and is
limited in destinations. T-SQL method is just bare bones, it is lacking compression,
encryption, notifications, and destinations. Ola’s script is just a more advanced version
of T-SQL method.