1. Trang chủ
  2. » Công Nghệ Thông Tin

Hướng dẫn học Microsoft SQL Server 2008 part 101 pot

10 125 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 652,93 KB

Nội dung

Nielsen c41.tex V4 - 07/23/2009 2:46pm Page 962 Part VI Enterprise Data Management A common technique is to rotate a set of five tapes for the weekly backups and another set of six tapes for the remaining daily backups. The weekly tapes would be labeled Sunday1, Sunday2, and so on, and the daily tapes would be labeled Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday. Palindromes also represent a great method for rotating backup tapes. A palindrome is a word, phrase, or number that’s the same backward or forward, such as ‘‘kayak’’ or ‘‘drab as a fool, aloof as a bard.’’ Some numbers when reversed and added to themselves will create a palindrome — for example, 236 + 632 = 868. Palindromes have a rich history: In ancient Greece they inscribed ‘‘Nipson anomemata me monan opsin,’’ meaning ‘‘wash the sin as well as the face,’’ on fountains. Using four tapes labeled A through D, a backup rotation might be ABCDCBA ABCDCBA Alternately, the palindrome method can be implemented so that each letter represents a larger interval, such as A for daily, B for weekly, C for monthly, and D for quarterly. Rotating backup tapes off site is an important aspect of recovery planning. Ideally, a contract should support an off-site recovery location complete with server and workstations. Performing backup with Management Studio The first backup must be a full database backup to begin the backup cycles. You can perform a database backup from Management Studio, selecting the database to be backed up. From the database context menu, or from the database Summary Page, select Tasks ➪ Back Up to open the Back Up Database form, shown in Figure 41-3. The backup source is configured in the General page: ■ Database: The database to be backed up. By default this is the current database in Manage- ment Studio. ■ Backup type: The type of backup — Full, Differential, or Transaction Log. If the database is set to the simple recovery model, transaction log will not be available. For full or differential backups, the whole database or selected files and filegroups can be backed up. ■ Copy Only Backup: Allows you to take copy only backup. This will back up all the data without affecting the overall backup and restore procedures for the database. Although this backup type was first introduced in SQL Server 2005, Management Studio in SQL Server 2005 did not support it. ■ Backup Component: The database component to be backed up: Database or File and File- groups. If the backup type selected is Transaction Log, the backup component is grayed out. Database indicates that the full database is backed up. File and Filegroups indicates that the specified files and/or filegroups are backed up. The rest of the Back Up Database form specifies the destination: ■ Name: The required name of the backup ■ Description: Optional additional information about the backup ■ Backup set will expire: SQL Server will prevent another backup from overwriting this backup until the expiration date. ■ Destination: Sets the destination tape file or disk file. If the current destination is incorrect, delete it and add the correct destination. ■ Contents: Displays the backups already in the selected destinations 962 www.getcoolebook.com Nielsen c41.tex V4 - 07/23/2009 2:46pm Page 963 Recovery Planning 41 FIGURE 41-3 The General page of the Back Up Database form The Options page of the Back Up Database form is shown in Figure 41-4. The Options page presents the following options: ■ Append to the existing backup set or Overwrite all existing backup sets: Determines whether the current backup will be added to the backup file or whether the backup media should be initialized and a new series of backups placed in them ■ Check media set name and backup set expiration: Verifies the name and expiration date for the backup ■ Verify backup when finished: Verifies that the backup is complete and the file is readable. This option does not compare the data in the backup with the data in the database, nor does it verify the integrity of the backup. ■ Perform checksum before writing to media: This verifies that the data read from the database is consistent with any checksum or torn-page detection on the database. It also calculates a checksum of the entire backup and saves it in the backup. This can help ensure that the database being backed up does not have any corruption due to the disk subsystem. 963 www.getcoolebook.com Nielsen c41.tex V4 - 07/23/2009 2:46pm Page 964 Part VI Enterprise Data Management FIGURE 41-4 The Options page of the Back Up Database form. ■ Continue on error: Allows backup to continue even after it encounters one or more errors ■ Unload the tape after backup: Directs the tape to eject, which helps prevent other backups from overwriting the backup file ■ Rewind the tape before unloading: This is enabled only if Unload the tape after backup is selected. This rewinds the tape before ejecting it. ■ Truncate the transaction log: Backs up the transaction log and truncates the inactive trans- actions to free log space. This is the default option for the Transaction Log backup. This option is available only when Transaction Log is selected for Backup Type on the General page. ■ Back up the tail of the log, and leave the database in the restoring state: Backs up the transaction log that has not yet been backed up. This option is equivalent to using NO_TRUNCATE or NORECOVERY in the BACKUP statement. This option is available only when Transaction Log is selected for Backup Type on the General page. ■ Set backup compression: Allows you to choose the default server-level backup compres- sion setting or ignore the server-level default and compress the backup or not compress the backup. At installation the default behavior is no backup compression. You can change this 964 www.getcoolebook.com Nielsen c41.tex V4 - 07/23/2009 2:46pm Page 965 Recovery Planning 41 default by setting the default server-level backup compression setting in Management Studio: Check the Compress Backup check box in the Database Settings tab of Server Properties. Backup compression is a new feature introduced in SQL Server 2008 Enterprise Edition. Compressed backup is smaller than uncompressed backup and therefore requires less I/O and increases backup speed significantly. However, this comes at the price of high CPU usage, which may impact other operations on the server. It is recommended to create low-priority compressed backups in a session whose CPU usage is limited by Resource Governor. For more on Resource Governor, see Chapter 69. Backing up the database with code The BACKUP command offers a few more options than Management Studio, and using the BACKUP command directly is useful for assembling SQL Server Agent jobs by hand, rather than with the Maintenance Plan Back Up Database Task. Without all the options and frills, the most basic BACKUP command is as follows: BACKUP DATABASE Databasename TO DISK = ‘file location’ WITH NAME = ‘backup name’; The following command backs up the AdventureWorks2008 database to a disk file and names the backup AdventureWorks2008Backup: BACKUP DATABASE AdventureWorks2008 TO DISK = ‘e:\AdventureWorks2008Backup.bak’ WITH NAME = ‘AdventureWorks2008Backup’; Result: Processed 17944 pages for database ‘AdventureWorks2008’, file ‘AdventureWorks2008_Data’ on file 1. Processed 2 pages for database ‘AdventureWorks2008’, file ‘AdventureWorks2008_Log’ on file 1. BACKUP DATABASE successfully processed 17946 pages in 7.954 seconds (17.625 MB/sec). The backup command has a few important options that deserve to be mentioned first: ■ TAPE (Backup To:): To back up to tape instead of disk, use the TO TAPE option and specify the tape-drive location: TO TAPE = ‘\\.\TAPE0’ ■ DIFFERENTIAL:CausestheBACKUP command to perform a differential backup instead of a full database backup. The following command performs a differential backup: BACKUP DATABASE AdventureWorks2008 TO DISK = ‘e:\AdventureWorks2008Backup.bak’ WITH DIFFERENTIAL, NAME = ‘AdventureWorks2008Backup’; 965 www.getcoolebook.com Nielsen c41.tex V4 - 07/23/2009 2:46pm Page 966 Part VI Enterprise Data Management ■ To back up a file or filegroup, list it after the database name. This technique can help organize backups. ■ PASSWORD: Use this to set the password for the backup. The password will be needed again to restore the backup. The password protection is weak and it is recommended to backup to tapes and store them in a secure location or backup to disks that have an adequate access control list (ACL). Avoid using the password option, as this feature will be removed in a future release of SQL Server. ■ COMPRESSION/NO_COMPRESSION: Overrides the server-level default backup compres- sion. COMPRESSION enables backup compression and performs checksums to detect media corruptions. ■ CHECKSUM/NO_CHECKSUM: Identical to the ‘‘Perform checksum before writing to media’’ option within Management Studio. ■ STOP_ON_ERROR/CONTINUE_AFTER_ERROR: Identical to the ‘‘continue on error’’ option within Management Studio. The BACKUP command has numerous additional options: ■ DESCRIPTION: Identical to the Description field within Management Studio ■ EXPIREDATE: Identical to Management Studio; prevents the backup from being overwritten before the expiration date ■ RETAINDAYS: The number of days, as an integer, before SQL Server will overwrite the backup ■ STATS = %: Tells SQL Server to report the progress of the backup in the percentage increment specified; the default increment is 10 percent. This option is very useful, particularly while troubleshooting a failed backup, as it gives you an idea of when the backup is failing. Also, for huge databases this indicates what percentage of the backup is completed. ■ BLOCKSIZE: Sets the physical block size in bytes. The default is 65,536 bytes for tape devices, and 512 otherwise. This option is usually not required, as backup automatically selects the correct block size of the device. If a backup to disk will later be copied to a CD/RW, try a block size of 2,048. ■ MEDIANAME: Specifies the name of the media volume. This option serves as a safety check: If the backup is being added to the media, the name must match. ■ MEDIADESCRIPTION: Writes an optional media description ■ MEDIAPASSWORD: Creates an optional media password that applies to the entire medium (disk file or tape). The first time the medium is created the password can be set. If the password is specified when the medium is created, then it must be specified every subsequent time the backup medium is accessed to add another backup or to restore. Avoid using the MEDIAPASSWORD option, as this feature will be removed in a future release of SQL Server. ■ INIT/NOINIT: Initializes the tape or disk file, thus overwriting all existing backup sets in the medium. SQL Server will prevent initialization if any of the backups in the medium have not expired or still have the number of retaining days. NOINIT is the default. 966 www.getcoolebook.com Nielsen c41.tex V4 - 07/23/2009 2:46pm Page 967 Recovery Planning 41 ■ NOSKIP/SKIP: This option ‘‘skips’’ the backup-name and backup-date checking that normally prevents overwriting backups. NOSKIP is the default. ■ NOFORMAT/FORMAT: FORMAT writes a new media header on media volumes used for backup and overwrites the existing backup sets; therefore the existing contents of the volume become unusable. NOFORMAT (default behavior) preserves the existing media header and backup sets. FORMAT automatically includes SKIP and INIT. The last options apply only when backing up to tape: ■ REWIND/NOREWIND: REWIND directs SQL Server to rewind the tape. The default is to REWIND. ■ UNLOAD/LOAD: UNLOAD automatically rewinds and unloads the tape. This is the default until the user session specifies load. ■ RESTART: This option has no effect. It is there for compatibility with previous versions of SQL Server. Verifying the backup with code Management Studio’s backup includes an option to verify the backup, and the T-SQL BACKUP com- mand does not. Management Studio actually calls the T-SQL RESTORE VERIFYONLY command after the backup to perform the verification: RESTORE VERIFYONLY FROM DISK = ‘e:\AdventureWorks2008Backup.bak’ Result: The backup set is valid. The verification has a few options, such as Eject tape after backup. Most of these verification options are for tapes and are self-explanatory. RESTORE VERIFYONLY does not actually restore the database. It only checks whether the backup is complete and readable. By default, it checks the backup checksums if they are present, and proceeds without verification if they are not present. Working with the Transaction Log Sometimes it seems that the transaction log has a life of its own. The space within the file seems to grow and shrink without rhyme or reason. If you’ve felt this way, you’re not alone. This section should shed some light on why the transaction log behaves as it does. Inside the transaction log The transaction log contains all the transactions for a database. If the server crashes, the transaction log is used for recovery by rolling back uncommitted partial transactions and by completing any transactions that were committed but not written to the data file. Virtually, the log can be imagined as a sequential list of transactions sorted by date and time. Physically, however, SQL Server writes to different parts of the physical log file in virtual blocks without a specific 967 www.getcoolebook.com Nielsen c41.tex V4 - 07/23/2009 2:46pm Page 968 Part VI Enterprise Data Management order. Some parts might be in use, making other parts available, so the log reuses itself in a loose round-robin fashion. The active and inactive divide The transactions in the transaction log can be divided into two groups (see Figure 41-5): ■ Active transactions are uncommitted and not yet written to the data file. ■ Inactive transactions are all those transactions before the earliest active transaction. FIGURE 41-5 The inactive transactions are all those prior to the oldest active transaction. Unused Inactive Transaction Log Committed Transactions Checkpoints Active Unused Uncommitted Transactions Oldest Uncommitted Transactions Because transactions are of varying duration, and are committed at different times, it’s very likely that committed transactions are in the active portion of the log. The active portion does not merely contain all uncommitted transactions, but all transactions since the start of the oldest uncommitted transaction. One very old uncommitted transaction can make the active portion appear unusually large. Transaction checkpoints Understanding how SQL Server uses checkpoints in the transaction log is important to understanding how the transaction log is backed up and emptied. For performance reasons, every time a database page is modified in memory, it is not written to disk immediately. SQL Server generates automatic checkpoints to write the dirty database pages from memory to disk. The time interval between automatic checkpoints is variable and depends on the amount of modifications made to the database and the recovery interval SQL Server configuration option. Checkpoints calculate the amount of work that must be done to recover the database during a system restart. A checkpoint also occurs under any of the following conditions: ■ When an ALTER DATABASE command is used ■ When the SQL Server is shut down If you used the SHUTDOWN WITH NOWAIT command to shut down SQL Server, then SQL Server will shut down without performing checkpoints in any database. ■ A minimally logged operation is performed in the database 968 www.getcoolebook.com Nielsen c41.tex V4 - 07/23/2009 2:46pm Page 969 Recovery Planning 41 ■ Database backup is done ■ When an activity requiring database shutdown or database restart is performed ■ When the number of log entries exceeds the estimated amount of work required by the SQL Server’s recovery interval configuration option ■ If the database is in simple recovery model and the transaction log becomes 70 percent full Checkpoints may be manually initiated with a CHECKPOINT command. Checkpoints perform the following activities: ■ Marks the checkpoint spot in the transaction log ■ Writes a checkpoint-log record, including the following: ■ The oldest active transaction ■ The oldest replication transaction that has not been replicated ■ A list of all active transactions ■ Information about the minimum work required to roll back the database ■ Marks the space before the oldest uncommitted transaction in a database with simple recovery for reuse ■ Writes all dirty data and log pages to disk Basically, a checkpoint gets everything up to date as best it can and then records the current state of the dividing line between active and inactive in the log. Backing up the transaction log Performing a transaction log backup is very similar to performing a full or differential backup, with a few notable differences. The T-SQL command is as follows: BACKUP LOG AdventureWorks2008 TO DISK = ‘e:\AdventureWorks2008Backup.bak’ WITH NAME = ‘AdventureWorks2008Backup’; Result: Processed 2 pages for database ‘AdventureWorks2008’, file ‘AdventureWorks2008_Log’ on file 2. BACKUP LOG successfully processed 2 pages in 0.118 seconds (0.095 MB/sec). The same media options apply to the transaction log backup that apply to the database backup; in addi- tion, two options are transaction-log specific: ■ NO_TRUNCATE\CONTINUE_AFTER_ERROR: Used for backing up the tail of the log of a damaged database that is offline and does not start. If the data files of a user database are damaged, a tail log backup succeeds only if the transaction log files are not damaged, the state of the database supports tail log backup, and the database does not contain any bulk logged operations. 969 www.getcoolebook.com Nielsen c41.tex V4 - 07/23/2009 2:46pm Page 970 Part VI Enterprise Data Management ■ NORECOVERY: Used to backup the tail of the log of a database that is online and for which you intend to perform RESTORE next. If the data file of the user database and master database is damaged, then provided the transaction log is not damaged, to minimize data loss you can still backup the tail of the transaction log as follows: 1. Rename the transaction log files. 2. Rebuild the master database with command-line setup. 3. Reapply any SQL Server updates that were previously applied. 4. Create a new user database. The number of data and log files needs to match the number of files of the damaged database. The size of the files can be different. 5. Stop SQL Server. 6. Delete the data files of the new database and replace the log files with the original transaction log files. 7. Start SQL Server. 8. The new database will fail to recover, as we deleted the data file. Run the following command to backup the tail of the log: BACKUP LOG Databasename TO DISK = ‘file location’ WITH NO_TRUNCATE; If only the data files of the user database are damaged and the master database and transaction log file of the user database are available, the tail of the log can be backed up directly by running the preceding BACKUP LOG command with the NO_TRUNCATE option. The transaction log cannot be backed up if any of the following conditions exist: ■ The database is using a simple recovery model. ■ The database is using a bulk-logged recovery model, a bulk-logged operation has been executed, and the database files are damaged. ■ Database files have been added or removed. In any of these cases, perform a full database backup instead. Truncating the log Updates and deletes might not increase the size of a data file, but to the transaction log every transaction of any type is simply more data. Left to its own devices, the transaction log will continue to grow with every data modification. The solution is to back up the inactive portion of the transaction log and then remove it. By default, backing up the transaction log will also truncate the log (refer to Figure 41-3). BACKUP LOG WITH NO_LOG and BACKUP LOG WITH TRUNCATE_ONLY are discontinued in SQL Server 2008. To truncate the log, either take regular transaction log backups or put the database in simple recovery model. 970 www.getcoolebook.com Nielsen c41.tex V4 - 07/23/2009 2:46pm Page 971 Recovery Planning 41 The transaction log and simple recovery model When the database is using a simple recovery model, the transaction log ensures that each committed transaction is written to the data file, and that’s it. When SQL Server performs a checkpoint and the transaction log is truncated, the free space of the transaction log fluctuates but the minimum is the size of the active portion of the transaction log. Under the simple recovery model, performing a manual checkpoint will truncate the log and free the log space. Truncating the log marks the inactive portion of the log for reuse and does not reduce the physical size of the transaction log. To reduce the physical size you need to run DBCC SHRINKFILE to manually shrink the log file. I have seen many DBAs running the DBCC SHRINKFILE command to shrink the log file right after log backup. I highly discourage this because DBCC SHRINKFILE can cause severe file-system fragmentation, as the files will likely need to grow again after they have been shrunk, causing performance degradation. Instead, it is important to correctly size the transaction log and perform frequent log backups to keep the size in check. To discover the operation that is preventing log truncation, use the log_reuse_wait_desc column of the sys.databases catalog view. Recovery Operations There are any number of reasons to restore a database, including the following: ■ A disk subsystem has failed. ■ A sleepy programmer forgot a WHERE clause in a SQL UPDATE statement and updated everyone’s salary to minimum wage. ■ The server melted into a pool of silicon and disk platters. ■ A large import worked, but with yesterday’s data. The best reason to restore a database is to practice the backup/restore cycle, and to prove that the recov- ery plan works. It is important to perform regular testing of your backup and restore strategy as a fire drill. Without confidence in the recovery, there’s little point to doing backups. Detecting the problem If a database file is missing, clicking the database in Management Studio pops up a message saying that the database is unavailable. To further investigate a problem, check the SQL Server Errorlog. In Manage- ment Studio, the log can be viewed under Management ➪ SQL Server Logs. SQL Server writes errors andeventstoanerrorlogfileinthe \Log directory under the MSSQL directory. SQL Server creates a new file every time the server is started. The six previous versions of the Errorlog file are saved in the same directory. Some errors may also be written to the Windows Application Event Log. To retain more than six Errorlogs, right-click SQL Server Logs in Management Studio and select Configure. 971 www.getcoolebook.com . the SQL Server Errorlog. In Manage- ment Studio, the log can be viewed under Management ➪ SQL Server Logs. SQL Server writes errors andeventstoanerrorlogfileinthe Log directory under the MSSQL. an ALTER DATABASE command is used ■ When the SQL Server is shut down If you used the SHUTDOWN WITH NOWAIT command to shut down SQL Server, then SQL Server will shut down without performing checkpoints. AdventureWorks2008 database to a disk file and names the backup AdventureWorks2008Backup: BACKUP DATABASE AdventureWorks2008 TO DISK = ‘e:AdventureWorks2008Backup.bak’ WITH NAME = ‘AdventureWorks2008Backup’; Result: Processed

Ngày đăng: 04/07/2014, 09:20

TỪ KHÓA LIÊN QUAN