Microsoft Press Configuring sql server 2005 môn 70 - 431 phần 6 pdf

98 270 0
Microsoft Press Configuring sql server 2005 môn 70 - 431 phần 6 pdf

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

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

454 Chapter 12 Using Transact-SQL to Manage Databases Quick Check ■ What is external fragmentation? Quick Check Answer ■ External fragmentation is the condition in which the physical order of index pages does not match the logical order. PRACTICE Using ALTER INDEX to Correct Index Fragmentation Levels DBAs need to learn how to manage index fragmentation levels by using the ALTER INDEX…REBUILD and ALTER INDEX…REORGANIZE statements. The following two practices take you through the process of correcting index fragmentation levels by using these two statements.  Practice 1: Use ALTER INDEX…REBUILD to Rebuild an Index In this practice, you rebuild an index by using the ALTER INDEX…REBUILD statement. 1. Start SSMS. 2. Connect to the instance containing the sample AdventureWorks database. 3. In Object Explorer, right-click the AdventureWorks database and choose New Query to open the Query Editor pane. 4. In the Query Editor pane, type in the following Transact-SQL statement to view current fragmentation levels, rebuild the indexes on the HumanRe- sources.Employee table, and view fragmentation levels after the rebuild: USE AdventureWorks; View the current fragmentation levels. SELECT index_id, avg_fragmentation_in_percent, avg_page_space_used_in_percent FROM sys.dm_db_index_physical_stats (DB_ID(‘AdventureWorks’), OBJECT_ID(‘HumanResources.Employee’),NULL, NULL, ’DETAILED’) WHERE index_id <> 0; does not return information about heaps Rebuild all indexes on the table. Create the indexes with a fill factor of 90. Allow the index operation to take place ONLINE ALTER INDEX ALL ON HumanResources.Employee REBUILD WITH (FILLFACTOR = 90, ONLINE = ON); View the fragmentation levels after the index rebuilds. SELECT index_id, avg_fragmentation_in_percent, avg_page_space_used_in_percent FROM sys.dm_db_index_physical_stats (DB_ID(‘AdventureWorks’), OBJECT_ID(‘HumanResources.Employee’),NULL, NULL, ’DETAILED’) WHERE index_id <> 0; does not return information about heaps C1262271X.fm Page 454 Friday, April 29, 2005 7:55 PM Lesson 1: Managing Index Fragmentation 455  Practice 2: Use ALTER INDEX…REORGANIZE to Reorganize an Index In this practice, you will reorganize an index by using the ALTER INDEX…REORGA- NIZE statement. 1. If necessary, start SSMS and connect to the instance containing the Adventure- Works sample database. Open the Query Editor pane. 2. In the Query Editor pane, type in the following Transact-SQL statement to view current fragmentation levels, reorganize the indexes on the HumanRe- sources.Employee table, and view the fragmentation levels after the reorganization: USE AdventureWorks; View the current fragmentation levels. SELECT index_id, avg_fragmentation_in_percent, avg_page_space_used_in_percent FROM sys.dm_db_index_physical_stats (DB_ID(‘AdventureWorks’), OBJECT_ID(‘HumanResources.Employee’),NULL, NULL, ’DETAILED’) WHERE index_id <> 0; does not return information about heaps Reorganize all indexes on the table. ALTER INDEX ALL ON HumanResources.Employee REORGANIZE; View the fragmentation levels after the index reorganization. SELECT index_id, avg_fragmentation_in_percent, avg_page_space_used_in_percent FROM sys.dm_db_index_physical_stats (DB_ID(‘AdventureWorks’), OBJECT_ID(‘HumanResources.Employee’),NULL, NULL, ’DETAILED’) WHERE index_id <> 0; does not return information about heaps Lesson Summary ■ Indexes become fragmented during INSERT, DELETE, and UPDATE opera- tions, and this fragmentation can degrade query performance. ■ Internal index fragmentation occurs when the index pages are not filled to the maximum amount allowed under the current fill factor setting. ■ External index fragmentation occurs when the physical ordering of index pages does not match the logical ordering of the pages. ■ You can check index fragmentation levels by running a SELECT statement against the sys.dm_db_index_physical_stats dynamic management function. ■ You can correct index fragmentation by executing either the ALTER INDEX…REORGANIZE or the ALTER INDEX…REBUILD Transact-SQL statement. C1262271X.fm Page 455 Friday, April 29, 2005 7:55 PM 456 Chapter 12 Using Transact-SQL to Manage Databases Lesson Review The following questions are intended to reinforce key information presented in this lesson. The questions are also available on the companion CD if you prefer to review them in electronic form. NOTE Answers Answers to these questions and explanations of why each answer choice is right or wrong are located in the “Answers” section at the end of the book. 1. You are a DBA tasked with maintaining an installation of SQL Server 2005.One of your jobs is to determine the index fragmentation levels for all user tables in your database. Which dynamic management view or function can you use to review index fragmentation levels? A. sys.dm_db_index_operational_stats B. sys.dm_db_index_usage_stats C. sys.dm_db_missing_index_details D. sys.dm_db_index_physical_stats 2. You are a DBA tasked with maintaining an installation of SQL Server 2005.You need to determine whether your tables contain external fragmentation. Which column would you use to find whether your indexes are externally fragmented? A. avg_fragment_size_in_pages B. avg_page_space_used_in_percent C. avg_fragmentation_in_percent D. avg_record_size_in_bytes 3. You are a DBA tasked with maintaining an installation of SQL Server 2005.One of your jobs is to correct the index fragmentation levels for all user tables in your database. During your fragmentation investigation, you determine that an index has external fragmentation levels greater than 30 percent. Which statement would you use to correct this amount of external fragmentation? A. ALTER INDEX…REBUILD B. ALTER INDEX REORGANIZE C. ALTER INDEX…DISABLE D. ALTER INDEX…SET STATISTICS_NORECOMPUTE = ON C1262271X.fm Page 456 Friday, April 29, 2005 7:55 PM Lesson 2: Managing Statistics 457 Lesson 2: Managing Statistics Another important aspect of achieving top query performance is the statistical information that SQL Server creates about the distribution of values in a column. During its evaluation of a query, the query optimizer uses these statistics to estimate the cost of using an index to satisfy the query. To ensure optimum query perfor- mance, you need to understand the importance of statistics and decide when to let SQL Server automatically generate and update them, and when to manually gener- ate and update them. After this lesson, you will be able to: ■ Explain the purpose of statistics. ■ Manage index and column statistics. Estimated lesson time: 25 minutes Understanding Statistics When SQL Server creates column and index statistics, the database engine sorts the values of the columns on which the statistics are being built and creates a histogram. Histograms are based on up to 200 values contained in the column, separated by intervals. The histogram specifies how many rows exactly match each interval value, how many rows fall within an interval, and the density of values contained within an interval. These statistics on column values help the query optimizer determine whether using an index improves query performance. SQL Server 2005 introduces additional information that is collected by statistics cre- ated on char, varchar, varchar(max), nchar, nvarchar, nvarchar(max), text, and ntext col- umns. This additional information, called a string summary, helps the query optimizer estimate the selectivity of query predicates on string patterns, which leads to better estimates of result set sizes when a query uses LIKE conditions. Automatic Statistics Generation When a DBA creates an index, the query optimizer stores statistical information about the indexed columns. Additionally, if the AUTO_CREATE_STATISTICS database option is set to ON, the database engine creates statistics on columns that are not con- tained in indexes but that are used in query predicates. C1262271X.fm Page 457 Friday, April 29, 2005 7:55 PM 458 Chapter 12 Using Transact-SQL to Manage Databases An additional benefit to having the AUTO_UPDATE_STATISTICS database option set to ON is that the query optimizer also automatically updates statistical information periodically as the data in the tables changes. This statistics update operation is initi- ated whenever the statistics used in a query execution plan fail a test for current statis- tics. This test is a random sampling across data pages taken either from the table or the smallest nonclustered index on the columns needed by the statistics. Almost always, statistical information is updated when approximately 20 percent of the data rows have changed; however, the query optimizer ensures that a minimum number of rows are sampled, with tables smaller than 8 MB being fully scanned to gather statistics. This test is important because when data in a column changes, index and column sta- tistics can become out of date. As a result, the query optimizer might make less-than- optimal decisions about how to process a query, which causes those queries to exe- cute with dramatically substandard performance. Manual Statistics Generation You can also manually create statistics. To create statistics on all eligible columns in all user tables in the current database by using just one statement, you can execute the sp_createstats system stored procedure. To create statistics on specific table or view columns, you can use the CREATE STATISTICS statement. To manually update statis- tics, you can execute the UPDATE STATISTICS statement or execute the sp_updatestats system stored procedure. And you can drop statistics by using the DROP STATISTICS statement. A key benefit of creating statistics manually is that you can create statistics that con- tain densities of values for a combination of columns. By having statistics for a com- bination of columns, the database engine could make a better estimate for query execution. Viewing Column Statistics Information SQL Server 2005 gives DBAs several ways to obtain information about column statistics: ■ The sp_autostats system stored procedure displays or changes the automatic UPDATE STATISTICS setting for a specific index and statistics or for all indexes and statistics for a specified table or indexed view in the current database. ■ The sys.stats catalog view displays a row for each statistic of a tabular object of the type U, V, or TF. C1262271X.fm Page 458 Friday, April 29, 2005 7:55 PM Lesson 2: Managing Statistics 459 ■ The sys.stats_columns catalog view displays a row for each column that is part of sys.stats statistics. ■ The STATS_DATE function returns the date that the statistics for the specified index were last updated. ■ The DBCC SHOW_STATISTICS statement displays the current distribution sta- tistics for the specified target on the specified table. Quick Check ■ Why are statistics important to query performance? Quick Check Answer ■ During its evaluation of a query, the query optimizer uses the statistical information to estimate the cost of using an index and determine the opti- mal query plan for a query. PRACTICE Manually Creating and Updating Statistics The following two practices walk you through the process of manually creating and updating statistics.  Practice 1: Create Statistics In this practice, you create statistics by using the CREATE STATISTICS statement. 1. If necessary, start SSMS and connect to the instance containing the Adventure- Works sample database. Open the Query Editor pane. 2. In the Query Editor pane, type the following Transact-SQL statement to view which columns in the HumanResources.Employee table do not have statistics built on them: USE AdventureWorks; Determine which columns do not have statistics on them. SELECT c.name FROM sys.columns c LEFT OUTER JOIN sys.stats_columns sc ON sc.[object_id] = c.[object_id] AND sc.column_id = c.column_id WHERE c.[object_id] = OBJECT_ID(‘HumanResources.Employee’) AND sc.column_id IS NULL ORDER BY c.column_id C1262271X.fm Page 459 Friday, April 29, 2005 7:55 PM 460 Chapter 12 Using Transact-SQL to Manage Databases You might see a result set like the one shown following (actual column names returned will depend upon your database environment): BirthDate MaritalStatus Gender SalariedFlag VacationHours SickLeaveHours CurrentFlag ModifiedDate 3. In the Query Editor pane, type the following Transact-SQL statements to create statistics on the columns in the HumanResources.Employee table that do not cur- rently have statistics on them, and then recheck for columns that do not have statistics: Create statistics for the columns needing statistics. CREATE STATISTICS st_BirthDate ON HumanResources.Employee (BirthDate) WITH FULLSCAN; CREATE STATISTICS st_MaritalStatus ON HumanResources.Employee (MaritalStatus) WITH FULLSCAN; CREATE STATISTICS st_Gender ON HumanResources.Employee (Gender) WITH FULLSCAN; CREATE STATISTICS st_SalariedFlag ON HumanResources.Employee (SalariedFlag) WITH FULLSCAN; CREATE STATISTICS st_VacationHours ON HumanResources.Employee (VacationHours) WITH FULLSCAN; CREATE STATISTICS st_SickLeaveHours ON HumanResources.Employee (SickLeaveHours) WITH FULLSCAN; CREATE STATISTICS st_CurrentFlag ON HumanResources.Employee (CurrentFlag) WITH FULLSCAN; C1262271X.fm Page 460 Friday, April 29, 2005 7:55 PM Lesson 2: Managing Statistics 461 CREATE STATISTICS st_ModifiedDate ON HumanResources.Employee (ModifiedDate) WITH FULLSCAN; Determine which columns still do not have statistics on them. SELECT c.name FROM sys.columns c LEFT OUTER JOIN sys.stats_columns sc ON sc.[object_id] = c.[object_id] AND sc.column_id = c.column_id WHERE c.[object_id] = OBJECT_ID(‘HumanResources.Employee’) AND sc.column_id IS NULL ORDER BY c.column_id;  Practice 2: Update Statistics In this practice, you will manually update statistics by using the UPDATE STATISTICS statement. 1. If necessary, start SSMS and connect to the instance containing the Adventure- Works sample database. Open the Query Editor pane. 2. In the Query Editor pane, type the following Transact-SQL statements to view when the statistics were last updated, update all statistics on the HumanRe- sources.Employee table, and check when the statistics were last updated: USE AdventureWorks; View date the statistics were last updated. SELECT ’Index Name’ = i.[name] , ’Statistics Date’ = STATS_DATE(i.[object_id], i.index_id) FROM sys.objects o INNER JOIN sys.indexes i ON o.name = ’Employee’ AND o.[object_id] = i.[object_id]; Update statistics on all indexes on the table. UPDATE STATISTICS HumanResources.Employee WITH FULLSCAN; View date the statistics were last updated. SELECT ’Index Name’ = i.[name] , ’Statistics Date’ = STATS_DATE(i.[object_id], i.index_id) FROM sys.objects o INNER JOIN sys.indexes i ON o.name = ’Employee’ AND o.[object_id] = i.[object_id]; C1262271X.fm Page 461 Friday, April 29, 2005 7:55 PM 462 Chapter 12 Using Transact-SQL to Manage Databases Lesson Summary ■ Statistics on table or view columns play an important role in optimizing query performance; the SQL Server query optimizer uses these statistics to evaluate the cost of using an index to satisfy a query. ■ When you create an index, the query optimizer automatically stores statistical information about the indexed columns. You can also set the AUTO_CREATE_STATISTICS database option to ON to have the database engine automatically create statistics on columns that are not contained in indexes but that are used in query predicates and to automatically update statis- tical information periodically as the data in the tables changes. ■ Alternatively, you can manually create and update statistics by using Transact- SQL statements and stored procedures. Lesson Review The following questions are intended to reinforce key information presented in this lesson. The questions are also available on the companion CD if you prefer to review them in electronic form. NOTE Answers Answers to these questions and explanations of why each answer choice is right or wrong are located in the “Answers” section at the end of the book. 1. Which Transact-SQL function shows the last time statistics were updated for a specified index? A. sys.stats_columns B. DBCC SHOWCONTIG C. DBCC SHOW_STATISTICS D. STATS_DATE 2. Which Transact-SQL statement allows SQL Server to automatically update sta- tistics? A. sp_autostats B. sys.stats C. UPDATE STATISTICS D. CREATE STATISTICS C1262271X.fm Page 462 Friday, April 29, 2005 7:55 PM Lesson 3: Shrinking Files 463 Lesson 3: Shrinking Files In SQL Server 2005, certain operations such as large delete operations or one-time data loads might leave database files larger than they need to be. SQL Server 2005 enables a DBA to shrink each file within a database to remove unused pages and regain disk space. And although the SQL Server database engine is designed to reuse space effectively, there are times when a database or a database file no longer needs to be as large as it once was. You might then need to shrink the database or file either through a manual process of shrinking all the database files or certain files individu- ally or by setting the database to automatically shrink at specified intervals. In this les- son, you learn how to determine when you should shrink database files and what Transact-SQL statements you can use to shrink databases and database files. After this lesson, you will be able to: ■ Determine when it is appropriate to shrink database files. ■ Use Transact-SQL statements to shrink databases and database files. Estimated lesson time: 15 minutes Shrinking Database Files Automatically SQL Server 2005 enables you to set a database option that allows the database engine to automatically shrink databases that have free space. When you set the ALTER DATABASE AUTO_SHRINK option to ON, the database engine periodically examines the database’s space usage and reduces the size of the database files for that database. CAUTION Be careful when allowing AUTO_SHRINK The AUTO_SHRINK option is set to OFF by default, and you should take care when setting this option to ON. Although the shrink process takes place in the background and does not affect users in the database, the process of shrinking a database can consume system resources, which can degrade the performance of the server. Also, continually shrinking and regrowing a database can lead to fragmentation at the file level, which often cannot be easily addressed in today’s 24 x 7 database environments. C1262271X.fm Page 463 Friday, April 29, 2005 7:55 PM [...]... | TSQL | SERVICE_BROKER | DATABASE_MIRRORING } ( MORE INFO Protocol-specific arguments For information about all the options available for configuring the protocol-specific arguments for an HTTP endpoint, see the SQL Server 2005 Books Online article “CREATE ENDPOINT (TransactSQL).” SQL Server 2005 Books Online is installed as part of SQL Server 2005 Updates for SQL Server. .. need C1 362 271X.fm Page 479 Friday, April 29, 2005 7: 56 PM Lesson 1: Understanding HTTP Endpoint Security 479 Lesson 1: Understanding HTTP Endpoint Security To communicate with SQL Server, an application must connect to a port number on which that SQL Server is configured to listen Previous SQL Server versions have left this connection point unsecured as well as unrestricted However, SQL Server 2005 has... indexed view in the database MORE INFO DBCC CHECKDB To see all the many options available with the DBCC CHECKDB command, see the SQL Server 2005 Books Online topic “DBCC CHECKDB (Transact -SQL) .” C1 262 271X.fm Page 470 Friday, April 29, 2005 7:55 PM 470 Chapter 12 Using Transact -SQL to Manage Databases DBAs should keep in mind the following best practices associated with running DBCC CHECKDB: ■ Because... necessary, start SSMS and connect to the instance containing the AdventureWorks sample database Open the Query Editor pane C1 262 271X.fm Page 466 Friday, April 29, 2005 7:55 PM 466 Chapter 12 Using Transact -SQL to Manage Databases 2 In the Query Editor pane, type the following Transact -SQL statements to check the current auto shrink setting for the database, set the database to shrink automatically, and then...C1 262 271X.fm Page 464 Friday, April 29, 2005 7:55 PM 464 Chapter 12 Using Transact -SQL to Manage Databases Shrinking Database Files Manually When you need to shrink a database, transaction log, or single database file to recover unused space, it is often a better choice to manually shrink the file rather than to let SQL Server 2005 perform the operation automatically... C1 362 271X.fm Page 484 Friday, April 29, 2005 7: 56 PM 484 Chapter 13 Working with HTTP Endpoints Lesson 2: Creating a Secure HTTP Endpoint You create HTTP endpoints to expose stored procedures and functions to SOAP requests from Web services You can use Transact -SQL statements or SQL Server Management Objects (SMOs) to create and manage HTTP endpoints; in this lesson, we will cover the Transact -SQL. .. statistics on columns in SQL Server 2005 databases ■ Review and understand the importance of column statistics by dropping column statistics on tables in a test database and then comparing query execution times before and after the statistics are dropped Practice 1 C1 262 271X.fm Page 4 76 Friday, April 29, 2005 7:55 PM 4 76 Chapter 12 Review ■ Understand the importance of up-to-date statistics by turning... 484 Before You Begin To complete the lessons in this chapter, you must have ■ SQL Server 2005 installed ■ A copy of the AdventureWorks sample database installed in the instance 477 C1 362 271X.fm Page 478 Friday, April 29, 2005 7: 56 PM 478 Chapter 13 Working with HTTP Endpoints Real World Michael Hotek In SQL Server 2000, you could expose stored procedures directly to a Web service Although this... any error messages 4 In the Query Editor pane, type the following Transact -SQL statement to execute the following statement to set the database back to multiple-user mode: Remove from single-user mode ALTER DATABASE AdventureWorks SET MULTI_USER; C1 262 271X.fm Page 472 Friday, April 29, 2005 7:55 PM 472 Chapter 12 Using Transact -SQL to Manage Databases Lesson Summary ■ You use the DBCC CHECKDB statement... data MORE INFO DBCC SHRINKDATABASE and DBCC SHRINKFILE For full details about executing the DBCC SHRINKDATABASE and DBCC SHRINKFILE statements, see the SQL Server 2005 Books Online topics “DBCC SHRINKDATABASE (Transact -SQL) ” and “DBCC SHRINKFILE (Transact -SQL) ,” respectively Shrinking the Transaction Log Database transaction logs are created with fixed boundaries in which you can shrink a transaction log . CHECKDB command, see the SQL Server 2005 Books Online topic “DBCC CHECKDB (Transact -SQL) .” C1 262 271X.fm Page 469 Friday, April 29, 2005 7:55 PM 470 Chapter 12 Using Transact -SQL to Manage Databases DBAs. instance containing the Adventure- Works sample database. Open the Query Editor pane. C1 262 271X.fm Page 465 Friday, April 29, 2005 7:55 PM 466 Chapter 12 Using Transact -SQL to Manage Databases 2. In. 463 Lesson 3: Shrinking Files In SQL Server 2005, certain operations such as large delete operations or one-time data loads might leave database files larger than they need to be. SQL Server 2005 enables

Ngày đăng: 09/08/2014, 09:21

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan