TABLE 41-2 Recovery Sequences Recovery Model Damaged Database File Damaged Transaction Log Simple 1 Restore full backup.. For example, under the full recovery model, the restore plan sel
Trang 1Recovery sequences
The two most important concepts about recovering a database are as follows:
■ A recovery operation always begins by restoring a full backup and then restores any additional differential or transactional backups The restore never copies only yesterday’s work It restores the entire database up to a certain point
■ There’s a difference between restore and recover A restore copies the data back into the database and leaves the transactions open Recovery is the process of handling the transactions
left open in the transaction log If a database-recovery operation requires that four files be restored, only the last file is restoredWITH RECOVERY
Only logins who are members of thesysadminsfixed server role can restore a database that doesn’t
currently exist.sysadminsanddb_ownerscan restore databases that do currently exist
The actual recovery effort depends on the type of damage and the previous recovery plans Table 41-2 is
a comparative listing of recovery operations
Performing the restore with Management Studio
As with theBACKUPcommand, there are numerous ways to launch the restore form within Management
Studio:
Select the database to be backed up From the context or Action menu select Tasks➪ Restore ➪
Database to open the SQL Server Restore Database form
TABLE 41-2
Recovery Sequences
Recovery Model Damaged Database File Damaged Transaction Log
Simple 1) Restore full backup
2) Restore latest differential backup (if needed)
It is very likely there are unapplied transactions lost with the transaction log and the database is inconsistent It
is recommended to fall back on your backups and use the steps docu-mented for ‘‘damaged database file.’’
Full or
Bulk-logged
1) Back up current transaction log with NO_TRUNCATEoption*
2) Restore full backup
3) Restore latest differential backup (if needed)
4) Restore all the transaction-log backups since the last differential or full backup All committed transactions will be recovered
1) Restore full backup
2) Restore latest differential backup (if needed)
3) Restore all the transaction-log backups since the last differential or full backup
Transactions made since the last backup will be lost
*If the database is using the bulk-logged recovery model and a bulk-insert operation occurred since the last
transaction-log backup, the backup will fail Transactions that occurred after the transaction-log backup will not
be recoverable.
Trang 2The Restore Database form, shown in Figure 41-6, does a great job of intelligently navigating the
poten-tial chaos of the backup sequences, and it always offers only legal restore options
FIGURE 41-6
Only the correct sequence of restoring from multiple backup files is possible from Management
Studio’s Restore Database form
The selection you make at the top of the form is the name of the database after the restore
The Restore Database form can restore database backups, file backups, or backups from a device (e.g a
tape drive) The Restore Wizard will present a hierarchical tree of backups, while the filegroups or file
restore lists the files and must be manually restored in the correct order
The ‘‘Select the backup sets to restore’’ option displays the available backups Management Studio
uses the backup history in themsdbdatabase and creates a restore plan For example, under the full
recovery model, the restore plan selects the full database backup followed by the most recent differential
database backup (if available), followed by subsequent log backups
If the backup history, stored inmsdb, is not available — because the server is being rebuilt or the
database is being restored to a different server — then use the Restore: From Device option to manually
select the specific backup disk file and backup instance within the file
Trang 3The process of one full backup, the second differential backup, and the following 15 transaction-log
backups can be correctly sequenced by selecting the final transaction log to be restored Restoring the 17
backup files is performed with a single click of the OK button
If one of the backup files being restored is a transaction log, the Point in Time Restore option becomes
available because only a transaction log can restore some of the transactions The point-in-time restore
will restore all transactions committed before the time selected
The Options page of the Restore Database form is shown in Figure 41-7
FIGURE 41-7
The Options page of the Restore Database form
The Options page of the Restore Database dialog offers a few significant options:
■ ‘‘Overwrite the existing database’’ disables a safety check that prevents Database A backup from being restored as Database B and accidentally overwriting an existing Database B
■ ‘‘Preserve the replication settings’’ preserves the replication settings when restoring a published database on a different SQL Server (other than the SQL Server where the database was cre-ated) This option is available only with the ‘‘Leave the database ready for use by rolling back the uncommitted transactions’’ option
Trang 4■ ‘‘Prompt before restoring each backup’’ prompts before continuing to restore the next backup
in the restore sequence This option is useful when you are restoring from tape backups and
need to swap tapes
■ ‘‘Restrict access to the restored database’’ restricts access to the restored database only to
members ofdb_owner,dbcreatoror sysadmin
■ Because it is very possible that the database is being restored to a different file location than
the original backup, the ‘‘Restore the database files as’’ section in the Options tab includes a
way to assign new file locations
■ ‘‘Leave the database ready for use by rolling back the uncommitted transactions’’ should be
used for restoring the final backup This option recovers the database and does not allow
additional transaction logs to be restored
■ ‘‘Leave the database non-operational, and do not roll back the uncommitted transactions’’
enables you to restore additional backups If you select this option, the ‘‘Preserve replication
settings’’ option is unavailable
■ ‘‘Leave the database in read-only mode’’ leaves the database in a standby mode in which the
database is available for limited read-only access
If only certain files or filegroups are being restored, then select Tasks➪ Restore ➪ File or Filegroups to
select the files or filegroups you wish to restore
Restoring with T-SQL code
Database backup is a regularly scheduled occurrence, so if SQL Server’s built-in Maintenance Plan
Wiz-ard isn’t to your liking, it makes sense to write some repeatable code to perform backups and set up
your own SQL Server Agent jobs
However, unless the backup plan is only a full backup, it’s difficult to know how many differential
back-ups or transaction-log backback-ups need to be restored; and because each backup file requires a separate
RESTOREcommand, it’s difficult to script the recovery effort beforehand without writing a lot of code
to examine themsdbtables and determine the restore sequence properly
The backupset table in the msdb database contains a row for each backup set You can
query this table to find information on all the successful backups.
TheRESTOREcommand will restore from a full, differential, or transaction-log backup:
RESTORE DATABASE (or LOG) DatabaseName
Optional-File or Filegroup or Page
FROM BackUpDevice
WITH
FILE = FileNumber,
PARTIAL,
NORECOVERY or RECOVERY or STANDBY = UnDoFileName,
REPLACE,
STOPAT datetime,
STOPATMARK = ‘markname’
STOPBEFOREMARK = ‘markname’
Trang 5To restore a full or differential backup, use theRESTORE DATABASEcommand; otherwise, use the
RESTORE LOGfor a transaction log To restore a specific file or filegroup, add its name after the
database name ThePARTIALoption specifies a partial restore that restores the primary filegroup and
any specified secondary filegroup(s)
A backup set often contains several backup instances For example, a backup set might consist of the
following:
1: Full backup 2: Differential backup
3, 4, 5, 6: Transaction-log backups 7: Differential backup
8, 9: Transaction-log backups TheWITH FILEoption specifies the backup to restore If it’s not included in the command, the first
backup instance is restored
If a password was created with the backup, the password is required to perform a restore from the
backup
Avoid using the password option, as this feature will be removed in a future release of SQL Server.
To restore one or more pages, usePAGE =‘file:page[, .n]’, wherePAGEindicates a list of one or
more files and pages,fileindicates the file ID containing the page to be restored,pageindicates the
page ID of the page to be restored in the file, andnindicates multiple pages can be specified
TheRECOVERY/NORECOVERYoption is vital to theRESTOREcommand Every time a SQL Server
starts, it automatically checks the transaction log, rolling back any uncommitted transactions and
completing any committed transactions This process is called recovery, and it’s a part of the ACID
properties of the database
Therefore, if the restore has theNORECOVERYoption, SQL Server restores the log without handling any
transactions Conversely,RECOVERYinstructs SQL Server to handle the transactions In the sequence of
the recovery operation, all the restores must have theNORECOVERYoption enabled except for the last
restore, which must have theRECOVERYoption enabled
Deciding betweenRECOVERYandNORECOVERYis one of the complications involved in trying to write
a script to handle any possible future recovery operation
TheSTANDBYoption allows the recovery effects to be undone
If the recovery operation includes a transaction-log restore, the recovery can stop before the end of the
transaction log The optionsSTOPATandSTOPATMARKwill leave the end of the transaction log
unre-stored TheSTOPATaccepts a time, and theSTOPATMARKrestores only to a transaction that was
cre-ated with a named mark TheSTOPBEFOREMARKoption restores everything up to the beginning of the
marked transaction
TheREPLACEoption creates the database and its related files even if another database already exists
with the same name
Chapter 26, ‘‘Creating DML Triggers,’’ details SQL Server transactions and how to create marked transactions.
Trang 6The following script demonstrates an example of a restore sequence that includes a full backup and two
transaction-log backups:
BackUp and recovery example
CREATE DATABASE Plan2Recover;
Result:
Command(s) completed successfully
Continuing:
USE Plan2Recover;
CREATE TABLE T1 (
PK INT Identity PRIMARY KEY,
Name VARCHAR(15)
);
Go
INSERT T1 VALUES (’Full’);
go
BACKUP DATABASE Plan2Recover
TO DISK = ‘e:\P2R.bak’
WITH
NAME = ‘P2R_Full’,
INIT;
Result:
(1 row(s) affected)
Processed 168 pages for database ‘Plan2Recover’, file ‘Plan2Recover’
on file 1
Processed 6 pages for database ‘Plan2Recover’, file ‘Plan2Recover_log’
on file 1
BACKUP DATABASE successfully processed 174 pages in 0.800 seconds
(1.690 MB/sec)
Continuing:
INSERT T1 VALUES (’Log 1’);
go
BACKUP Log Plan2Recover
TO DISK = ‘e:\P2R.bak’
WITH
NAME = ‘P2R_Log’;
Result:
(1 row(s) affected)
Processed 6 pages for database ‘Plan2Recover’, file ‘Plan2Recover_log’
on file 2
Trang 7BACKUP LOG successfully processed 6 pages in 0.113 seconds (0.393 MB/sec)
Continuing:
INSERT T1 VALUES (’Log 2’);
go BACKUP Log Plan2Recover
TO DISK = ‘e:\P2R.bak’
WITH NAME = ‘P2R_Log’;
Result:
(1 row(s) affected) Processed 1 pages for database ‘Plan2Recover’, file ‘Plan2Recover_log’
on file 3
BACKUP LOG successfully processed 1 pages in 0.082 seconds (0.005 MB/sec)
Continuing:
SELECT * FROM T1;
Result:
-
(3 row(s) affected)
At this point the server is hit with a direct bolt of lightning and all drives are fried, with the exception
of the backup files The following recovery operation goes through the full backup and the two
transaction-log backups Notice theNORECOVERYandRECOVERYoptions:
NOW PERFORM THE RESTORE Use Master;
RESTORE DATABASE Plan2Recover FROM DISK = ‘e:\P2R.bak’
With FILE = 1, NORECOVERY;
Result:
Processed 168 pages for database ‘Plan2Recover’, file ‘Plan2Recover’
on file 1
Processed 6 pages for database ‘Plan2Recover’, file ‘Plan2Recover_log’
on file 1
Trang 8RESTORE DATABASE successfully processed 174 pages in 0.168 seconds
(8.050 MB/sec)
Continuing:
RESTORE LOG Plan2Recover
FROM DISK = ‘e:\P2R.bak’
With FILE = 2, NORECOVERY;
Result:
Processed 0 pages for database ‘Plan2Recover’, file ‘Plan2Recover’
on file 2
Processed 6 pages for database ‘Plan2Recover’, file ‘Plan2Recover_log’
on file 2
RESTORE LOG successfully processed 6 pages in 0.028 seconds
(1.586 MB/sec)
Continuing:
RESTORE LOG Plan2Recover
FROM DISK = ‘e:\P2R.bak’
With FILE = 3, RECOVERY;
Result:
Processed 0 pages for database ‘Plan2Recover’, file ‘Plan2Recover’
on file 3
Processed 1 pages for database ‘Plan2Recover’, file ‘Plan2Recover_log’
on file 3
RESTORE LOG successfully processed 1 pages in 0.004 seconds
(0.122 MB/sec)
To test the recovery operation:
USE Plan2Recover;
Select * from T1;
Result:
-
(3 row(s) affected)
As this script shows, it is possible to recover using T-SQL, but in this case Management Studio beats
code as the best way to accomplish the task
Trang 9System Databases Recovery
So far, this chapter has dealt only with user databases, but the system databases are important to the
recovery operation as well Themasterdatabase contains key database and security information, and
theMSDBdatabase holds the schedules and jobs for SQL Server, as well as the backup history A
com-plete recovery plan must include the system databases
Master database
Themasterdatabase, by default, uses the simple recovery model Using only full backups for the
masterdatabase is OK; it’s not a transactional database
Backing up the master database
Themasterdatabase is backed up in the same manner as user databases Be sure to back up the
masterdatabase when doing any of the following:
■ Creating or deleting databases
■ Modifying security by adding logins or changing roles
■ Modifying any server or database-configuration options Because theMSDBdatabase holds a record of all backups, back up themasterdatabase and then the
MSDB
Recovering the master database
If themasterdatabase is corrupted or damaged, SQL Server won’t start Attempting to start SQL
Server will have no effect Attempting to connect to the instance with Management Studio will invoke a
warning that the server does not exist or that access is denied The only solution is to first rebuild the
masterdatabase using the command-line setup (as shown next), reapply any SQL Server updates, start
SQL Server in single-user mode, and restore themasterdatabase
1 Rebuild themasterdatabase using the following command-line setup:
setup /QUIET /ACTION=REBUILDDATABASE /INSTANCENAME="<instance name>"
/SQLSYSADMINACCOUNTS="<DomainName\UserName >" /SAPWD="<password>"
■ setup.exeis either from your original installation media or the ‘‘local’’setup.exeas found in the 100\Setup Bootstrap\Release directory
■ The/QUIETswitch suppresses all error messages
■ The/ACTION=REBUILDDATABASEswitch rebuilds all the system databases
■ The/INSTANCENAMEswitch specifies the name of your SQL Server named instance Use MSSQLServerfor ‘‘<instance_name>’’ for the default instance.
■ The/SQLSYSADMINACCOUNTSswitch corresponds to the currently logged in domain user running this rebuild process The user must be a member of the SQL Server instance’s sysadmin server role
■ The/SAPWDswitch is used to indicate a new SA password if you configured SQL Server for mixed authentication
Trang 10A new feature has been added to rebuilding the system databases The system databases
used for rebuilding the local system databases do not come from the original installation
media and are located locally in the \BINN\Templates folder, and setup.exe is located in the 100\Setup
Bootstrap \Release folder Also notice that the switches have changed compared to SQL Server 2005.
2 Run the following from the command prompt to start a default instance of SQL Server in
single-user mode:
sqlservr.exe -m
To start a named instance of SQL Server in single-user mode, run the following:
sqlservr.exe -m -s <instancename>
3 Reapply any SQL Server updates, service packs, and hotfixes that were previously applied to
the SQL Server
4 Restore themasterdatabase as you would a user database If amasterbackup is not
available, then recreate all missing entries for your user databases, logins, endpoints, and so
forth
If the masterdatabase is accessible, start SQL Server in single-user mode and then restore themaster
database as you would a user database
Rebuilding the master database rebuilds the msdb and model databases too, so after
rebuilding the databases restore the system databases ( master , msdb , model ) from the most
recent good backup.
Rebuilding the master database installs all system databases to their initial location If initially one or
more system databases were moved to a different location, then a similar move is required again now.
MSDB system database
Like themasterdatabase, themsdbdatabase, by default, uses the simple recovery model
Because themsdbdatabase contains information regarding SQL Server Agent jobs and schedules, as well
as the backup history, it should be backed up whenever you do the following:
■ Perform backups
■ Save SSIS packages
■ Create new SQL Server Agent jobs
■ Configure SQL Server Agent mail or operators
■ Configure replication
■ Schedule tasks
Themsdbdatabase is backed up in the same way that a user database is backed up
To restore themsdbdatabase, you do not need to put the server in single-user mode, as you do with
themasterdatabase However, it’s still not a normal restore, because without a currentmsdb,
Man-agement Studio is not aware of the backup history Therefore, themsdbbackup can’t be chosen as a
backup database but must be selected as a backup device