Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 45 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
45
Dung lượng
2,66 MB
Nội dung
200 CHAPTER 7 ■ DATABASE BACKUPS, RECOVERY, AND MAINTENANCE 3. After execution, you should see output similar to the following, where the transaction log has been successfully backed up and placed on file 4: 100 percent processed. Processed 4 pages for database 'ApressFinancial', file 'ApressFinancial_log' on file 4. BACKUP LOG successfully processed 4 pages in 0.135 seconds (0.235 MB/sec). Restoring a Database Now that the data has been backed up, what if you need to complete a restore? As has been mentioned, there are two scenarios where a restore could be required: from a backup or when a media failure occurs. The second type of restore is not one you wish to perform, but you could set it up by creating a long-running transaction and then simply switching your computer off—not one of life’s greatest ideas to do deliberately! This book therefore will not be demonstrating this option, and it is not really for a beginner to attempt. However, I will discuss the concept within this section of the chapter. The first option, a simple restore, is easy to replicate and perform, and this will be the option we will be looking at. You can choose between two means to restore the database: SQL Server Management Studio and T-SQL. This is a scenario that you hope you will never perform in a production environment, but it will happen. If you just need a restore within the development environment to remove test data and get back to a stable predefined set of data to complete the testing, then this next section should help you. It might also be that you do a weekly refresh of your user test region from a production backup. Before completing the restore, let’s first modify the ApressFinancial database to prove that the restore works, as there is no data within the database yet to prove the restore has worked by that method. Keep in mind, however, that a restore will restore not only the data structures, but also the data, the permissions, and other areas of the database not yet covered in the book—for example, views, stored procedures, and so on. Restoring Using SQL Server Management Studio The restore demonstrated in the following example will be a complete database restore of our ApressFinancial database. In other words, it will restore all the full and differential backups taken. Try It Out: Restoring a Database 1. Add a new column to the ShareDetails.Shares table using the following code in a Query Editor pane: USE ApressFinancial GO ALTER TABLE ShareDetails.Shares ADD DummyColumn varchar(30) Dewson_958-7C07.fm Page 200 Tuesday, July 1, 2008 9:33 AM CHAPTER 7 ■ DATABASE BACKUPS, RECOVERY, AND MAINTENANCE 201 2. Once you have confirmed that the column has been added by looking in the Object Explorer, we can now use the backup we finished earlier to restore the database, which will remove the changes we have just completed. From the Object Explorer window, select the ApressFinancial database, right-click, and select Tasks ➤ Restore ➤ Database. This brings up the dialog box shown in Figure 7-8. It is possible to change the database you wish to restore by changing the name in the To Database combo box or by simply overwriting the name that is there. The second option, To a Point in Time, is used if you are restoring the database as well as rolling forward changes recorded in the transaction log. This situation is similar to the scenario mentioned earlier about a power failure or hard drive failure. As we are not doing this here, leave this option as it is. When taking a backup, details are stored in msdb, but it is possible to restore a database from a backup that is not in msdb. For example, if you are rebuilding a server due to corruption, and msdb was one of the databases corrupted, it is necessary to have the option of finding a backup file and restoring from that instead. Or perhaps the last full backup taken is not the backup you wish to restore. This might occur in a development scenario where you wish to restore to a backup before major changes were done that you wish to remove. There would be no transaction log involved or required to be involved, therefore restoring to a point in time would not be a valid scenario. This is where you could use the From Device option. By selecting this option and clicking the ellipsis to the right, you can navigate to any old backup files. Finally, you can click which of the items in the backup you wish to restore. The default is all files to be selected, as you can see in Figure 7-8. The settings shown will give us a backup that is as fresh as possible (the Most Recent Possible value for the To a Point in Time setting). Figure 7-8. Restoring a database—General tab Dewson_958-7C07.fm Page 201 Tuesday, July 1, 2008 9:33 AM 202 CHAPTER 7 ■ DATABASE BACKUPS, RECOVERY, AND MAINTENANCE 3. Moving to the Options page, shown in Figure 7-9, there are a number of points to consider: • Overwrite the Existing Database: This is the most likely option to be enabled for a normal restore. You would disable it if you wished to create a restore on the same server but where the restore would alter the name of the database. You cannot have any items not backed up within the transaction log; if you do, the restore will fail. • Preserve the Replication Settings: A more advanced option for when a database is sending changes to another database. For the time being, leave this option disabled. • Prompt Before Restoring Each Backup: If you wish a prompt message before each restore file is activated, then select this. This is ideal if you need to swap media over. • Restrict Access to the Restored Database: You may wish to check out the database after a restore to ensure the restore is what you wish, or in a production environment to run further checks on the database integrity. • Restore the Database Files As: This grid allows you to move or rename the MDF and LDF files. • Leave the Database Ready to Use: This option defines whether users can immediately connect and work with the data after the restore. If a transaction is in progress, such as deleting rows within a table, then the connection could occur once the deletion has been rolled back and the table is back in its “original” state. • Leave the Database Non-operational: With this option, you can indicate that the database has been partially restored and you are unsure if you need to perform additional actions. If a transaction is in progress, such as deleting a table, then whatever has been deleted will still be deleted and will not be rolled back. • Leave the Database in Read-Only Mode: A combination of the first two options. If a transaction is in progress, such as deleting rows in a table, then the connection could occur once the deletion has been rolled back. However, the changes are also kept in a separate file, so that any of these actions that have been rolled back can be reapplied. This might happen if there are several actions within a transaction and some can be reapplied. Dewson_958-7C07.fm Page 202 Tuesday, July 1, 2008 9:33 AM CHAPTER 7 ■ DATABASE BACKUPS, RECOVERY, AND MAINTENANCE 203 Figure 7-9. Restoring a database—Options tab 4. Once you have the option settings you require, a quick click of OK performs the restore. You should see the message in Figure 7-10. If you then move back to the database after clicking OK, you will see that the column we just added has been “removed” when you look in Object Explorer. Figure 7-10. Restore successful Dewson_958-7C07.fm Page 203 Tuesday, July 1, 2008 9:33 AM 204 CHAPTER 7 ■ DATABASE BACKUPS, RECOVERY, AND MAINTENANCE Restoring Using T-SQL Using the wizard is a pretty fast way to restore a database, and when under pressure, it may even be the best way forward. However, it is not the most flexible way of performing a restore, as some options that are available via T-SQL are not in this wizard. Some of these options were covered when we performed a backup, such as performing checksums when transferring data from the media device back to the database or unloading media at the end of the restore. If there is also a password on the backup medium, this option is not available within the wizard, but you can use passwords with T-SQL. Being comfortable building a restore via T-SQL is important in becoming a more profi- cient and professional developer or administrator. The syntax for restoring a database is similar to that for database backups. After looking at the syntax, we will then go through the options you will not be familiar with. RESTORE DATABASE { database_name | @database_name_var } [ FROM <backup_device> [ , n ] ] [ WITH [ { CHECKSUM | NO_CHECKSUM } ] [ [ , ] { CONTINUE_AFTER_ERROR | STOP_ON_ERROR } ] [ [ , ] FILE = { file_number | @file_number } ] [ [ , ] KEEP_REPLICATION ] [ [ , ] MEDIANAME = { media_name | @media_name_variable } ] [ [ , ] MEDIAPASSWORD = { mediapassword | @mediapassword_variable } ] [ [ , ] MOVE 'logical_file_name' TO 'operating_system_file_name' ] [ , n ] [ [ , ] PASSWORD = { password | @password_variable } ] [ [ , ] { RECOVERY | NORECOVERY | STANDBY = {standby_file_name | @standby_file_name_var } } ] [ [ , ] REPLACE ] [ [ , ] RESTART ] [ [ , ] RESTRICTED_USER ] [ [ , ] { REWIND | NOREWIND } ] [ [ , ] STATS [ = percentage ] ] [ [ , ] { STOPAT = { date_time | @date_time_var } | STOPATMARK = { 'mark_name' | 'lsn:lsn_number' } [ AFTER datetime ] | STOPBEFOREMARK = { 'mark_name' | 'lsn:lsn_number' } [ AFTER datetime ] } ] [ [ , ] { UNLOAD | NOUNLOAD } ] ] The options we have not yet covered are as follows: • KEEP_REPLICATION: When working with replication, consider using this option. Replication is when changes completed in one database are automatically sent to another database. The most common scenario is when you have a central database replicating changes to satellite databases, and possibly vice versa. • MOVE: When completing a restore, the MDF and LDF files that are being restored have to be placed where they were backed up from. However, by using this option, you can change that location. • RECOVERY | NORECOVERY | STANDBY: These three options are the same, and in the same order, as their counterparts (in parentheses) in the wizard: Dewson_958-7C07.fm Page 204 Tuesday, July 1, 2008 9:33 AM CHAPTER 7 ■ DATABASE BACKUPS, RECOVERY, AND MAINTENANCE 205 • RECOVERY (Leave the Database Ready to Use): This option defines that after the restore is finished, users can immediately connect to and work with the data. If a transaction is in progress, such as updating rows in a table, then not until the updates have been rolled back and therefore the table is back in its “original” state will connections to the database be allowed. • NORECOVERY (Leave the Database Non-operational): With this option, you are indicating that the database has been partially restored, and you are unsure whether you need to perform additional actions. If a transaction is in progress, such as inserting rows in a table, then the insertions will not be rolled back. This allows additional restores to get to a specific point in time. • STANDBY (Leave the Database in Read-Only Mode): A combination of the first two options. If a transaction is in progress, such as deleting rows in a table, then the deletion will be rolled back. However, the changes are also in a separate file, so that any of these actions that have been rolled back can be reapplied. This might happen if several actions occurred within a transaction and some can be reapplied. • REPLACE: This works the same as the wizard option Overwrite the Existing Database. • RESTART: If a restore is stopped partway through, then using this option will restart the restore at the point it was stopped. • RESTRICTED_USER: Use this with the RECOVERY option to only allow users in specific restricted groups to access the database. Use this to allow further checking by a database owner, or by the dbowner, dbcreator, or sysadmin roles. • STOPAT | STOPATMARK | STOPBEFOREMARK: Used to specify a specific date and time at which to stop the restore. The syntax for restoring the transaction log is exactly the same, with the only difference being the definition: you are completing a LOG rather than a DATABASE restore: RESTORE LOG { database_name | @database_name_var } <file_or_filegroup_or_pages> [ , f ] [ FROM <backup_device> [ , n ] ] [ WITH [ { CHECKSUM | NO_CHECKSUM } ] [ [ , ] { CONTINUE_AFTER_ERROR | STOP_ON_ERROR } ] [ [ , ] FILE = { file_number | @file_number } ] [ [ , ] KEEP_REPLICATION ] [ [ , ] MEDIANAME = { media_name | @media_name_variable } ] [ [ , ] MEDIAPASSWORD = { mediapassword | @mediapassword_variable } ] [ [ , ] MOVE 'logical_file_name' TO 'operating_system_file_name' ] [ , n ] [ [ , ] PASSWORD = { password | @password_variable } ] [ [ , ] { RECOVERY | NORECOVERY | STANDBY = {standby_file_name | @standby_file_name_var } } ] [ [ , ] REPLACE ] [ [ , ] RESTART ] [ [ , ] RESTRICTED_USER ] [ [ , ] { REWIND | NOREWIND } ] [ [ , ] STATS [=percentage ] ] [ [ , ] { STOPAT = { date_time | @date_time_var } | STOPATMARK = { 'mark_name' | 'lsn:lsn_number' } [ AFTER datetime ] Dewson_958-7C07.fm Page 205 Tuesday, July 1, 2008 9:33 AM 206 CHAPTER 7 ■ DATABASE BACKUPS, RECOVERY, AND MAINTENANCE | STOPBEFOREMARK = { 'mark_name' | 'lsn:lsn_number' } [ AFTER datetime ] } ] [ [ , ] { UNLOAD | NOUNLOAD } ] ] Try It Out: Restoring Using T-SQL 1. Open up an empty Query Editor pane and enter the following code. This will add the column that we want to see “removed” after a restore. USE ApressFinancial GO ALTER TABLE ShareDetails.Shares ADD DummyColumn varchar(30) 2. Now replace this code with the restore code that follows. Don’t execute any of the code just yet, as this piece of code is the first part only. Recall that when performing the backups, FILE 2 was the FULL backup taken. This is what the first restore will do. ■Note Ensure that the FROM DISK option is all on one line. Also recall that FILE = 2 may be FILE = 3 or any other number, depending on the backups taken, and this may be the case with different file numbers as you progress. USE Master GO RESTORE DATABASE [ApressFinancial] FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Backup\ ApressFinancial.bak' WITH FILE = 2, NORECOVERY, NOUNLOAD, REPLACE, STATS = 10 GO 3. Continue the code with the second part of the restore, which will be the differential backup restore. This uses FILE 3 from the backup set. RESTORE DATABASE [ApressFinancial] FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Backup\ ApressFinancial.bak' WITH FILE = 4, NORECOVERY, NOUNLOAD, REPLACE, STATS = 10 GO 4. The final part of the restore operation is to restore the transaction log file. Once all this code is in, you can run it all. RESTORE LOG [ApressFinancial] FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Backup\ ApressFinancial.bak' WITH FILE = 5, NOUNLOAD, STATS = 10 5. Once the code has fully executed, you should see results similar to those listed here: Dewson_958-7C07.fm Page 206 Tuesday, July 1, 2008 9:33 AM CHAPTER 7 ■ DATABASE BACKUPS, RECOVERY, AND MAINTENANCE 207 13 percent processed. 22 percent processed. 31 percent processed. 40 percent processed. 54 percent processed. 63 percent processed. 72 percent processed. 81 percent processed. 90 percent processed. 100 percent processed. Processed 176 pages for database 'ApressFinancial', file 'ApressFinancial' on file 2. Processed 1 pages for database 'ApressFinancial', file 'ApressFinancial_log' on file 2. RESTORE DATABASE successfully processed 177 pages in 0.284 seconds (5.105 MB/sec). 24 percent processed. 48 percent processed. 72 percent processed. 97 percent processed. 100 percent processed. Processed 32 pages for database 'ApressFinancial', file 'ApressFinancial' on file 3. Processed 1 pages for database 'ApressFinancial', file 'ApressFinancial_log' on file 3. RESTORE DATABASE successfully processed 33 pages in 0.066 seconds (4.088 MB/sec). 100 percent processed. Processed 0 pages for database 'ApressFinancial', file 'ApressFinancial' on file 4. Processed 4 pages for database 'ApressFinancial', file 'ApressFinancial_log' on file 4. RESTORE LOG successfully processed 4 pages in 0.013 seconds (2.441 MB/sec). We can now move back to the ShareDetails.Shares table and check that the column added has now been removed. You may have to perform a refresh within Object Explorer first to see the changes. Restoring a database in production will in most instances take place under pressure, as the database will have become corrupt or been inadvertently damaged. The production system is obviously down and not working, and we have irate users wanting to know how long before the system will be up. This is hopefully the worst-case scenario, but it is that sort of level of pressure that we will be working under when we have to restore the database. Therefore, having the correct backup strategy for your organization based on full, differential, and transaction log backups is crucial. Full database backups for a system that requires high availability so that the restore takes the least amount of time may be what you need. Detaching and Attaching a Database Now that we can back up and restore a database, we have other methods available for dealing with the database. There may be a time in the life of our SQL Server database when we have to move it from one server to another, or in fact just from one hard drive to another. For example, perhaps we currently have ApressFinancial on our C drive, and this is getting full, so we would like to move our database to another hard drive. Or perhaps we are moving from an old slower server to a new faster Dewson_958-7C07.fm Page 207 Tuesday, July 1, 2008 9:33 AM 208 CHAPTER 7 ■ DATABASE BACKUPS, RECOVERY, AND MAINTENANCE server or a server on a better network. By detaching and reattaching the database, we can do this simply and easily. I would like to make a couple of points here; they may seem straightforward and really obvious, but better to mention them than cause problems at a later stage. First of all, no updates can be occur- ring, no jobs can be running, and no users can be attached. Secondly, just in case, take a full backup before moving the database. This may add time to the process, but it is better to be safe than sorry. Ensure that where you are moving the database to has enough disk space, not only for the move, but also for expected future growth; otherwise, you will be moving your database twice. You should not attach your database to a server without immediately completing a backup on the new server after- ward; this way, you can ensure that the databases are protected in their new state. Detaching a database physically removes the details from the SQL Server master and msdb data- bases, but does not remove the files from the disk that it resides on. However, detaching the database from SQL Server then allows you to safely move, copy, or delete the files that make up the database, if you so desire. This is the only way that a database should be physically removed from a server for moving it. Detaching and Attaching Using SQL Server Management Studio We’ll start by using SSMS to detach and attach a database. Try It Out: Detaching a Database 1. First of all, it is necessary to ensure that nobody is logged in to the database, and even if someone is, that the user is not doing any updates. For the moment, I want you to ignore this and to have a connection. Ensure that SQL Server Management Studio is running and that there is a Query Editor pane with a connection to the ApressFinancial database. Find the ApressFinancial database in Object Explorer and ensure that is selected. Right-click and select Tasks ➤ Detach. 2. This brings up the Detach Database dialog box for the ApressFinancial database, as shown in Figure 7-11. We haven’t removed all the connected users, so you can do this by selecting the Drop Connections check box. The second option, Update Statistics, means that the SQL Server statistics for indexes and so on will be updated before the database is detached. The information is stored separately from the other data files in SQL Server, so selecting this option ensures that when the database is detached that the files are not lost and therefore don’t need re-creating. The status is Not Ready due to the message indicating that there is still “2 Active connection(s).” Although you only have one Query Editor open, the second connection is for the T-SQL IntelliSense. 3. In this example select the Drop Connections box. However, in a production environment, this could be very dan- gerous, so you should not select it without some thought. You can then click OK to finish detaching the database. That’s it. The database is detached, is no longer part of SQL Server, and is ready to be removed or even deleted. If you check the Object Explorer in SQL Server Management Studio, you will see that the database is no longer listed. Detaching a database, although seemingly a simple and innocuous operation, has the potential to be fraught with problems and worries. As the example demonstrated, ensuring that there are no users attached to the database at the time of detaching is not as easy as it first may seem. Setting up the database options to eliminate connections or to stop updates is only pos- sible once everyone has been removed from connections to the database. There is no easy way of removing connections safely, as you never know what an application with a connection to the database is doing. You could remove a connection Dewson_958-7C07.fm Page 208 Tuesday, July 1, 2008 9:33 AM CHAPTER 7 ■ DATABASE BACKUPS, RECOVERY, AND MAINTENANCE 209 that is in the middle of processing. If you are going down the route of detaching the database, though, there is an obvious reason to do this, such as moving servers and removing the database, so you would have a plan of action to do this. Users would have been notified days or weeks in advance, and the database owner would have coordinated a date and time when nobody should be connected. Also, the database owner would be around if there were any problems, and he or she could make the decision to kill any connections left hanging around. Figure 7-11. Detaching a database Detaching the database is a process that removes entries within the SQL Server system tables to inform SQL Server that this database is no longer within this instance of SQL Server and therefore cannot be used. It is as simple as that. If you are removing the database completely, then you will need to delete the files from the directory they were created in. It is possible to detach the database using a system stored procedure, although this does not let you kill the connections. This has to be done via a T-SQL command. We need to reattach the database before being able to demonstrate this, so let’s do that now. This would occur on our new SQL Server instances after physically moving the files. Dewson_958-7C07.fm Page 209 Tuesday, July 1, 2008 9:33 AM [...]... MAINTENANCE This section will detail how to set up and test Database Mail You will see how to implement Database Mail within the maintenance task created in the preceding section Try It Out: Setting Up Database Mail 1 To configure Database Mail, you need to create a Mail Profile for SQL Server to use SQL Server Agent must be running to be able to create a Mail Profile (If SQL Server Agent is not running, as... stability, SMTP runs in a process outside SQL Server Even if there are SMTP issues, SQL Server should not be affected if the STMP process stops for any reason On top of this, SQL Server comes with built-in system stored procedures and functionality to use SMTP to send out mail These features are collectively called Database Mail Dewson_958-7C07.fm Page 235 Tuesday, July 1, 2008 9:33 AM CHAPTER 7 ■ DATABASE... possible to drop and re-create them • Update Statistics: Statistics are kept to aid the execution of queries These can get out of date if you don’t have the option set to keep these up to date, and this option can update them at this point • Clean Up History: This removes historical information such as job history for a set period of time • Execute SQL Server Agent Job: This executes a predefined SQL Server. .. for the maintenance plan You can then choose the server that the maintenance plan is on This covers instances when your Management Studio is connected to more than one server For example, if you have a connection to your ISP that you have a SQL Server installation on, and the ISP wants you to set up your own maintenance plan, you would change the server to that location More likely, you will need to. .. maintenance job to mail out results of its work It is possible in SQL Server 2008 to use SMTP mail to send out notifications from your server This means that you don’t need to install a MAPI client, such as Microsoft Outlook, because SMTP processing is contained within a Windows install The fact that you don’t need another product on the server has benefits in terms of making your server more stable To supplement... the data is not required This method tends to be used to keep the structure within a source repository such as Visual SourceSafe It is also useful for setting up empty databases when moving from development to testing or into production Try It Out: Producing the Database SQL 1 Ensure that SQL Server Management Studio is running and that you have expanded the server so that you can see the ApressFinancial... single schedule for the entire plan when you want to run the tasks synchronously This is the option you want to take at this time 6 At the bottom of the screen shown in Figure 7-23, it is possible to either set the Schedule to a date and time or leave the plan with no schedule and to run it manually The aim is to run this automatically, so click the Change button You will now see the screen shown in Figure... database to many client sites, but it’s not the only way of doing it Detaching a database is simply removing it logically from a server, but keeping the physical files This then allows these files to be moved to anywhere, from another hard drive to a DVD, for further copying to a client computer if need be, and then reattaching the database at the other end Detaching a database removes entries from the... involves choosing where to write out the details of the maintenance plan and each step's success or failure For the moment, place the output in a report Later in the chapter, you will see how to mail that report from SQL Server 18 Similar to when we produced a script for the database, clicking Next brings up a summary of what will be performed within the plan (see Figure 7- 36) Here you can review what... View ➤ History from the same pop-up menu used to execute the plan On the left, you can view other logs that are generated within SQL Server Figure 7-40 Log file viewer showing the maintenance plan has run Setting Up Database Mail It would be better to be notified about jobs that have failed rather than having to monitor each job as it processes manually One of the ways to do this would be to build a . you wish to restore to a backup before major changes were done that you wish to remove. There would be no transaction log involved or required to be involved, therefore restoring to a point. There may be a time in the life of our SQL Server database when we have to move it from one server to another, or in fact just from one hard drive to another. For example, perhaps we currently. means that the SQL Server statistics for indexes and so on will be updated before the database is detached. The information is stored separately from the other data files in SQL Server, so selecting