CHAPTER 14 Database Backup and Restore Backup Scenarios Typically, several different types of backups are used in a comprehensive backup plan.. LISTING 14.1 Full Backups with Transaction
Trang 1ptg CHAPTER 14 Database Backup and Restore
FIGURE 14.4 Backing up the transaction log in SSMS
backup or manual truncation, the log can fill to a point where it will use up all the space
on your disk
Creating Transaction Log Backups with SSMS
The same backup screen utilized for database backups in SSMS can also be used for
trans-action log backups Figure 14.4 shows the Back Up Database window with Transtrans-action Log
selected as the backup type A device must be selected to write the backup to, and some
additional options on the Options page that relate to the transaction log are enabled
Creating Transaction Log Backups with T-SQL
When you back up a transaction log by using T-SQL, you use the BACKUP LOG command,
which includes all the previously listed options except the DIFFERENTIAL option
(Differential backups do not apply to transaction logs.) Several additional options are
available for transaction log backups The following abbreviated syntax for the BACKUP
LOG command shows the options used exclusively for backing up transaction logs:
BACKUP LOG { database_name | @database_name_var }
TO < backup_device > [ , n ]
[ [ MIRROR TO < backup_device > [ , n ] ] [ next-mirror ] ]
[ WITH
Trang 2
[ [ , ] NO_TRUNCATE ]
[ [ , ] { NORECOVERY | STANDBY = undo_file_name } ]
The options specific to BACKUP LOG are discussed in detail in the following sections
The NO_TRUNCATE Option
You use the NO_TRUNCATE option when the log is available, but the database is not This
option prevents the truncation of the transaction log after a backup occurs Under normal
circumstances, the BACKUP LOG command not only writes to the transaction log, but also
signals a checkpoint for the database to flush any dirty buffers from memory to the
database files This behavior becomes a problem when the media containing the database
is unavailable and you must capture the current contents of a log to a backup file for
recovery If you last did a log backup four hours ago, this would mean the loss of all the
input since then If your log is on a separate disk that is not damaged, you have those
four hours of transactions available to you, but BACKUP LOG fails because it can’t run a
checkpoint on the data files You run BACKUP LOG with the NO_TRUNCATE option, and the
log is backed up, but the checkpoint is not run because the log is not actually cleared
You now have this new log backup to restore as well, enabling recovery to the time of
failure The only transactions lost are those that were not yet committed
The NORECOVERY option causes the tail of the log to be backed up and leaves the database
in a RESTORING state, which allows additional transaction logs to be applied, if necessary
The tail of the log is the active portion of the log that contains transactions not yet
backed up This “tail” is critical in restore situations in which all committed transactions
are reapplied Typically, the NORECOVERY option is used with the NO_TRUNCATE option to
retain the contents of the log
The STANDBY option also backs up the tail of the log, but it leaves the database in a
read-only/standby state The read-only state allows inquiry on the database and allows
additional transaction logs to be applied to the database as well undo_file_name must be
supplied with the STANDBY command so that transactions not committed and rolled back
at the time of the backup can be reapplied if additional transaction logs are applied to the
database This STANDBY option produces the same results as executing BACKUP LOG WITH
NORECOVERY followed by a RESTORE WITH STANDBY command
NOTE
As mentioned earlier, Microsoft has removed the NO_LOG and TRUNCATE_ONLY options
available with earlier versions of SQL Server, including SQL Server 2005 Setting a
database to use the simple recovery model is the alternative to these options
Trang 3CHAPTER 14 Database Backup and Restore
Backup Scenarios
Typically, several different types of backups are used in a comprehensive backup plan
These backups are often combined to produce maximum recoverability while balancing
the load on the system and amount of time to recover the database The following backup
scenarios outline some of the ways SQL Server backups are used
NOTE
Many of the examples that follow utilize a backup directory named
c:\mssql2008\backup If you are interested in running some of these examples on
your own system, you need to create this directory on the database server first before
running the scripts that reference this directory You can use backup and data
directo-ries different from the default directory to simplify the directory structure for the SQL
Server files Typically, these directories should not be on the C: drive, but the C: drive
is used here for simplicity
Full Database Backups Only
A full database backup, without the use of other database backups, is often found in
nonproduction environments where the loss of transactional data is relatively
unimpor-tant Some development environments are good examples of this In these environments,
a nightly full backup is sufficient to ensure that recent Data Definition Language (DDL)
changes and the related development data for the day are captured If a catastrophic
failure occurs during the day and causes a restore to occur, the database can be restored
from the prior night’s backup The following example shows a full backup of the
AdventureWorks2008 database:
Full Database Backup to a single disk device
BACKUP DATABASE [AdventureWorks2008]
TO DISK = N’C:\mssql2008\backup\AdventureWorks2008.bak’
WITH NOFORMAT, INIT, NAME = N’AdventureWorks2008-Full Database Backup’,
SKIP, NOREWIND, NOUNLOAD, STATS = 10
The sole use of daily full database backups needs to be carefully considered The benefits
of limited administration and limited backup space requirements have to be weighed
against the costs of losing an entire day’s transactions
Full Database Backups with Transaction Log Backups
Compared to making a full database backup only, a more comprehensive approach to
database backups includes the use of transaction log backups to augment the
recoverabil-ity of full database backups Transaction log backups that are taken periodically capture
incremental database activity that can be applied to a full database backup during
data-base restore
You need to measure the frequency of the transaction log backup against the tolerance for
data loss For example, if the requirement is to prevent no more than one hour’s worth of
Trang 4work, the transaction log backups should be taken hourly If the media on which the
backup is stored is accessible, you should lose no more than one hour’s worth of data
As mentioned earlier, the database must be placed in full or bulk-logged recovery mode to
capture transaction log backups Listing 14.1 shows the commands necessary to place the
AdventureWorks2008 database in full recovery mode, the required backup to establish a
base, followed by the command to perform the actual transaction log backup
LISTING 14.1 Full Backups with Transaction Logs
First need to change the recovery model from simple to full
so that the tlogs are available for backup
ALTER DATABASE [AdventureWorks2008] SET RECOVERY FULL WITH NO_WAIT
*** A Full database backup must be taken after the
*** recovery mode has been changed
*** in order to set a base for future tlog backups
*** If the full backup is not taken
*** then tlog backups will fail
The Following full backup utilizes two devices on the same drive
Often times multiple devices are backed up to different drives
Backing up to different drives
can speed up the overall backup
time and help when you are running low on space on a drive
where your backups are written
BACKUP DATABASE [AdventureWorks2008]
TO DISK = N’C:\mssql2008\backup\AdventureWorks2008_Full_Dev1.bak’,
DISK = N’C:\mssql2008\backup\AdventureWorks2008_Full_Dev2.bak’
WITH NOFORMAT, NOINIT, SKIP, NOREWIND, NOUNLOAD, STATS = 10
Transaction log backups can be taken now that a base has been established
The following tlog backup is written to a single file
BACKUP LOG [AdventureWorks2008]
TO DISK = N’C:\mssql2008\backup\log\AdventureWorks2008_FirstAfterFull.trn’
WITH NOFORMAT, INIT, NAME = N’AdventureWorks2008-Transaction Log Backup’,
SKIP, NOREWIND, NOUNLOAD, STATS = 10, CHECKSUM
Differential Backups
Differential backups can be used to reduce the amount of time required to restore a
data-base and can be particularly useful in environments where the amount of data that
changes is limited Differential backups capture only the database extents that have
changed since the last database backup—typically, a full database backup
Trang 5CHAPTER 14 Database Backup and Restore
FIGURE 14.5 A backup plan that includes differential backup
The addition of differential backups to a plan that includes full database backups and
transaction log backups can significantly improve the overall recovery time The
differen-tial database backup eliminates the need to apply any transaction log backups that have
occurred from the time of the last full backup up until the completion of the differential
backup Figure 14.5 depicts a backup plan that includes full database backups, transaction
log backups, and differential backups The differential backups are executed on a daily
basis between the full backups
It is important to remember that differential backups are cumulative and contain all
changes since the last differential base There is no need to apply previous differential
backups if the new differential base has not been established For example, in the backup
plan shown in Figure 14.5, if a media failure occurred in the middle of the day on January
3, the differential backup that would be used is the one taken at the beginning of the day
on January 3; the differential backup that occurred on January 2 would not be needed
The full backup from January 1, the differential from January 3, and any transaction log
backups that had occurred since the differential on January 3 would be used to restore the
database
You can create differential backups by using SSMS or T-SQL The following example
demonstrates the creation of a differential backup for the AdventureWorks2008 database
using T-SQL:
BACKUP DATABASE [AdventureWorks2008]
TO DISK = N’C:\mssql2008\backup\AdventureWorks2008_Diff2.bak’
WITH DIFFERENTIAL , NOFORMAT, INIT,
NAME = N’AdventureWorks2008-Differential Database Backup’,
SKIP, NOREWIND, NOUNLOAD, STATS = 10
Partial Backups
Partial backups are useful when read-only files or filegroups are part of a database Listing
14.2 contains the commands necessary to add a read-only filegroup to the
AdventureWorks2008 database The commands in Listing 14.2 do not perform a partial
Trang 6backup, but they do modify a sample database so that a partial database would make
sense
LISTING 14.2 Adding a Read-Only Filegroup to a Database
Need to add a read only filegroup first to demonstrate
ALTER DATABASE AdventureWorks2008
ADD FILEGROUP ReadOnlyFG1
GO
Add a file to the Filegroup
ALTER DATABASE AdventureWorks2008
ADD FILE
( NAME = AdventureWorks2008_ReadOnlyData,
FILENAME = ‘C:\mssql2008\data\AdventureWorks2008_ReadOnlyData.ndf’,
SIZE = 5MB,
MAXSIZE = 100MB,
FILEGROWTH = 5MB) TO FILEGROUP ReadOnlyFG1
go
Create a table on the ReadOnly filegroup
CREATE TABLE AdventureWorks2008.dbo.MyReadOnlyTable
( FirstName varchar(50),
LastName varchar(50),
EMailAddress char(1000) )
ON ReadOnlyFG1
Insert some data into the new read only Filegroup
insert AdventureWorks2008.dbo.MyReadOnlyTable
select LastName, FirstName, ‘xxx’
from AdventureWorks2008.person person
Make the filegroup readonly
ALTER DATABASE [AdventureWorks2008] MODIFY FILEGROUP [ReadOnlyFG1] READONLY
When you have a filegroup that contains read-only data, a partial backup can be valuable
The partial backup by default excludes any read-only filegroups and backs up only the
read/write data that could have changed
Listing 14.3 contains three separate backup commands that relate to the partial backup
The first backup command is not a partial backup but instead backs up the read-only
file-group If the only filegroup is not backed up prior to the partial backup, the
read-only filegroup is backed up, as is part of the partial backup The second backup command
creates the actual partial backup The key parameter in this backup is
READ_WRITE_FILEGROUPS, which causes the backup to skip the read-only data The third
backup command in Listing 14.3 shows that it is possible to perform a partial backup that
includes the read-only data as well This command includes a specific reference to the
read-only filegroup, which causes it to be backed up as well
Trang 7CHAPTER 14 Database Backup and Restore
LISTING 14.3 Making a Partial Backup
Need to backup the readonly filegroup that was created
or it will be included in the partial backup
BACKUP DATABASE [AdventureWorks2008]
FILEGROUP = N’ReadOnlyFG1’
TO DISK = N’C:\mssql2008\backup\AdventureWorks2008_ReadOnlyFG.bak’
WITH NOFORMAT, NOINIT, NAME = N’AdventureWorks2008-Full Filegroup Backup’,
SKIP, NOREWIND, NOUNLOAD, STATS = 10
Create the Partial Database Backup
It will not contain the data from readonly filegroup
The partial database backup can be restored without affecting
the data in the readonly filegroup
BACKUP DATABASE [AdventureWorks2008] READ_WRITE_FILEGROUPS
TO DISK = N’C:\mssql2008\backup\AdventureWorks2008_Partial.bak’
WITH NOFORMAT, INIT, NAME = N’AdventureWorks2008-Partial Database Backup’,
SKIP, NOREWIND, NOUNLOAD, STATS = 10
It is possible to backup the readonly filegroup(s) as well
by listing the readonly filegroups in the backup command as shown in the
following backup command
BACKUP DATABASE [AdventureWorks2008] FILEGROUP = ‘ReadOnlyFG1’,
READ_WRITE_FILEGROUPS
TO DISK = N’C:\mssql2008\backup\AdventureWorks2008_Partial_WithReadOnly.bak’
WITH NOFORMAT, INIT, NAME = N’AdventureWorks2008-Partial Database Backup’,
SKIP, NOREWIND, NOUNLOAD, STATS = 10
File/Filegroup Backups
Much of our discussion thus far has focused on backing up an entire database, but it is
possible to back up only particular files or a group of files in a filegroup A SQL Server
database, by default, has only two files: the data file (with the file extension mdf) and the
log file (with the extension ldf) You can add additional files and filegroups that contain
these files to extend the database beyond the original two files These additional files are
often data files added to larger databases that require additional space With very large
databases, performing a full backup that contains all the database files can take too much
time In such a case, the individual files or filegroups can be backed up separately,
enabling you to spread out the backup
Listing 14.4 shows the T-SQL command that can be used to back up the read-only file you
added to the AdventureWorks2008 database in Listing 14.3
Trang 8LISTING 14.4 Creating a File Backup
BACKUP DATABASE [AdventureWorks2008] FILE = ‘AdventureWorks2008_ReadOnlyData’
TO DISK = N’C:\mssql2008\backup\AdventureWorks2008_ReadOnlyData.bak’
WITH NOFORMAT, INIT, NAME = N’AdventureWorks2008-Readonly File Backup’,
SKIP, NOREWIND, NOUNLOAD, STATS = 10
There is some additional administrative overhead associated with file and filegroup
backups Unlike a full database backup that produces one file that contains the entire
database, the file backups do not stand by themselves and require other backups to be able
to create the entire database You need to keep the following points in mind when
performing file and filegroup backups:
A file or filegroup backup does not back up any portion of the transaction log To
restore a file or filegroup backup, you must have the transaction log backups since
the last file or filegroup backup, including the tail of the log, for the database system
to ensure transactional consistency This also implies that the database must be in
full or bulk-logged recovery because these are the only models that support
transac-tion log backups
Individual file or filegroup backups can be restored from a full database backup
Point-in-time recovery is not permitted with file or filegroup backups
Differential backups can be combined with file or filegroup backups These
differen-tial backups capture only those extents that have changed since the file or filegroup
backup was made
File and filegroup backups can be very powerful options for very large databases, but you
need to ensure that the relevant backups can be accounted for In all backup situations,
the key to a successful plan is testing your backup strategy; this is particularly true with
file and filegroup backups
Mirrored Backups
The use of mirrored backups can help diminish the possibility of losing a database backup
Database backups can be your lifeline to recovery, and you do not want to lose them
Mirrored backups simultaneously write the backup information to more than one media
set You can mirror the backup to two, three, or four different media sets Listing 14.5
gives an example of a mirrored backup that writes two different media sets
LISTING 14.5 Creating a Mirrored Backup
BACKUP DATABASE AdventureWorks2008
TO disk = ‘C:\mssql2008\backup\AdventureWorks2008_Mirror1a.bak’,
Trang 9CHAPTER 14 Database Backup and Restore
disk = ‘C:\mssql2008\backup\AdventureWorks2008_Mirror1b.bak’
MIRROR TO disk = ‘c:\mssql2008\backup\AdventureWorks2008_Mirror2a.bak’,
disk = ‘C:\mssql2008\backup\AdventureWorks2008_Mirror2b.bak’
WITH FORMAT,
MEDIANAME = ‘AdventureWorks2008MirrorSet’
The example in Listing 14.5 is simplistic and demonstrates only the backup’s capability to
write to two different locations At the end of the backup example, four files will exist
Each pair of files can be used to restore the database In the real world, a backup like that
in Listing 14.5 would write to two different disk or tape drives Storing the media on the
same drive is very risky and does not give you all the advantages a mirror can afford
Copy-Only Backups
If you want a backup that will not affect future or past backups, copy-only backups are for
you The copy-only backup allows you to make a database or log backup without
identify-ing the backup as one that should be included in a restore sequence
Contrast this with a full database backup: If a full database backup is taken, the
informa-tion related to this backup is captured in the system tables This backup can form the base
for other backups, such as transaction log backups or differential backups, and must be
retained to be able to restore the backups that depend on the base
The following example shows a copy-only backup; the COPY_ONLY parameter is the key to
creating this kind of backup:
BACKUP DATABASE [AdventureWorks2008]
TO DISK = N’C:\mssql2008\backup\AdventureWorks2008_COPY.bak’
WITH COPY_ONLY
Compressed Backups
How would you like to create a backup file that is smaller and takes less time to create?
Sign me up This has got to be an option that the average database user would love to use
Compressed backups are smaller in size than uncompressed backups The reduced size of a
compressed backup typically requires less device I/O and can therefore reduce backup
times significantly
You must be aware that there are some trade-offs, however First, this feature is available
only with Enterprise Edition or Developer Edition Second, the creation of a compressed
backup can impact on the performance of concurrent operations on your database server
while the backup is being created Specifically, CPU usage increases during the backup
This may or may not be an issue for you Consider that many full database backups are
taken during off-hours, so there are more CPU cycles available during this time Either
way, you should monitor the CPU usage using compression versus not using compression
to evaluate the impact Another option is to create low-priority compressed backups in a
Trang 10session whose CPU usage is limited by the Resource Governor (For more information on
using the Resource Governor, see Chapter 40, “Managing Workloads with the Resource
Governor.”)
When you get past these hurdles, the creation of a compressed backup is straightforward
One option is to set a server option so that all backups are created as compressed files by
default You can use the sp_configure stored procedure to set the backup compression
default If this is set to true, future backups will be created in a compressed format unless
the backup is specifically created with the NO_COMPRESS option
You also have the option of creating a compressed backup regardless of the server option
This is done using the new COMPRESSION option available with the T-SQL BACKUP
command The following example shows how to create an AdventureWorks2008 backup in
the compressed format:
BACKUP DATABASE [AdventureWorks2008]
TO DISK = N’C:\MSSQL2008\Backup\AdventureWorks2008_compressed.bak’
WITH NOFORMAT, NOINIT,
NAME = N’AdventureWorks2008-Full Database Backup’,
SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 10
The compression is quite impressive In some simple tests performed on the
AdventureWorks2008 database, the compressed backup was one fourth the size of a
noncompressed backup The compression ratio varies depending on the type of data in
the database that you are backing up but can be as good as or better than 4:1
System Database Backups
The system databases are the master, model, msdb, resource, tempdb, and distribution
databases SQL Server uses these databases as part of its internal workings All these
data-bases should be part of your backup plan, except for resource and tempdb You can find
detailed descriptions of these databases in Chapter 7, “SQL Server System and Database
Administration.” The important point to remember about all these databases is that they
contain key information about your SQL Server environment The msdb database contains
information about backups and scheduled jobs The master database contains information
about all the user databases stored on the server This information can change over time
To ensure that you do not lose the information the system databases contain, you should
back up these databases as well Typically, nightly full database backups of these databases
suffice You can use the same backup T-SQL syntax or SSMS screens that you use for a user
databases to accomplish this task
Restoring Databases and Transaction Logs
A database restore allows a database or part of a database to be recovered to a state that it
was in previously This state includes the physical structure of the database, configuration
options, and data contained in the database The options you have for recovery are
heavily dependent on the backup plan you have in place and way you have configured