La descarga está en progreso. Por favor, espere

La descarga está en progreso. Por favor, espere

Rendimiento de Microsoft® SQL Server TM 2000

Presentaciones similares


Presentación del tema: "Rendimiento de Microsoft® SQL Server TM 2000"— Transcripción de la presentación:

1 Rendimiento de Microsoft® SQL Server TM 2000
KEY MESSAGE: SQL Server 2000 Performance SLIDE BUILDS: None SLIDE SCRIPT: HI, my name is _____________, and I would like to welcome everybody to this TechNet technical seminar. In this series of seminars. Microsoft provides key technical information for the IT professionals on current topics that affect today’s business environment. Today’s topic is SQL Server 2000 Performance – how you can enhance your use of SQL Server 2000 by using performance measurement and management tools supplied by Microsoft. SLIDE TRANSITION: Let’s have a look at the topics we’ll cover today … ADDITIONAL INFORMATION FOR PRESENTER: Microsoft Corporation

2 Lo que vamos a cubrir Bloqueos Procesador de consultas
Optimización de consultas Configuración del sistema Monitoreo de rendimiento KEY MESSAGE: What we will cover today SLIDE BUILDS: None SLIDE SCRIPT: Today’s presentation will cover a lot of territory: First, we have bloqueos, including different types, and scopes of locks, Next the Procesador de consultas, and how it compiles, optimizes, and executes queries, And Ajuste de consultas, including the Ajuste de consultas Wizard, and index creation, Then Configuración del sistema, for the SQL Server 2000 system, and Finally Monitoreo del rendimiento, including the SQL Profiler, system stored procedures, and the System Monitor. You’ll come away from this session with a much clearer idea of what tools are available to help you monitor and improve the performance of your SQL system. SLIDE TRANSITION: As you can see, this session covers some pretty technical topics. On the next slide, let’s check the prerequisites for you to get the most out of this session. ADDITIONAL INFORMATION FOR PRESENTER:

3 Prerrequisitos de la sesión
Esta sesión asume que usted comprende los aspectos básicos de Windows® 2003 Server/Windows® 2000 Server SQL Server 2000 Monitor del sistema KEY MESSAGE: prerequisites for this session SLIDE BUILDS: None SLIDE SCRIPT: Today’s presentation will cover a lot of technical topics on SQL Server 2000. To get the most benefit out of this presentation, you should understand the fundamentals of Windows® 2000 Server SQL Server 2000 and System Monitor This is a Level 200 session. SLIDE TRANSITION: Next, the agenda for today… ADDITIONAL INFORMATION FOR PRESENTER: Nivel 200

4 Agenda Bloqueos Procesador de consultas Optimización de consultas
Configuración del sistema Monitoreo del rendimiento KEY MESSAGE: Agenda topics – current topic is locking. SLIDE BUILDS: None SLIDE SCRIPT: Here’s our agenda for today – we’ll look at Different types and scopes of bloqueos, the operation of the Procesador de consultas, How we can do Ajuste de consultas, Configuración del sistema, and Finally Monitoreo del rendimiento, including the SQL Profiler, system stored procedures, and the System Monitor. Our first agenda topic here is bloqueos. SLIDE TRANSITION: We’ll start by looking at the Lock Manager … ADDITIONAL INFORMATION FOR PRESENTER:

5 Administrador de bloqueos Qué hace por usted
Adquiere y libera bloqueos Mantiene la compatibilidad entre los modos de bloqueos Resuelve interbloqueos Escala bloqueos Utiliza 2 sistemas de bloqueos Bloqueos de datos compartidos Pestillos internos para datos internos y concurrencia de índices KEY MESSAGE: what the Lock manager does SLIDE BUILDS: None SLIDE SCRIPT: Basically the lock manager acquires and releases locks on request. What and when the lock is acquired depends on the operation being performed. It does this as well as maintaining compatibility between lock modes, resolving deadlocks, and escalating locks. The lock manager provides two separate locking systems. The first system affects all fully shared data and provides row locks, page locks, and table locks for tables, data pages, text pages, and leaf-level index pages. The second system is used internally for index concurrency control, controlling access to internal data structures, and retrieving individual rows of data pages. This second system uses latches, which are less resource intensive than locks and provide performance optimization. SLIDE TRANSITION: Next, we’ll cover locking granularity… ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 14, pages You could use full-blown locks for all locking, but because of their complexity, they would slow down the system if they were used for all internal needs. Lock escalation example - if you are reading every row in a table each with a lock, the lock manager can change this to a table lock which is more efficient that holding lots of row level locks. Read operations acquire shared locks while write operations acquire exclusive locks. Update locks are acquired during the initial portion of an update operation when the data is read.

6 Bloqueos Granularidad de bloqueos para los datos del usuario
KEY MESSAGE: Show granularity for locks SLIDE BUILDS: SLIDE SCRIPT: This figure shows the possible lock levels in a table – row, page, and table locks. Note that if the table has a clustered index, the data rows are at the leaf level of the clustered index and they are locked with key locks instead of row locks. TRANSITION: Now we will see the available Lock Isolation Levels ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 14, pages SQL Server can lock user data resources (not system resources, which are protected with latches) at the table, page, or row level. SQL Server also locks index keys and ranges of index keys. Tabla Página Página Página Fila Fila Fila

7 Niveles de aislamiento de bloqueos
KEY MESSAGE: Show available Lock Isolation Levels SLIDE BUILDS: None SLIDE SCRIPT: This slide shows the available Lock Isolation Levels. SQL Server supports all four transaction isolation levels specified by ANSI and ISO: Serializable, Repeatable Read, Read Committed, and Read Uncommitted. The read committed Isolation level is the default. SLIDE TRANSITION: Now we will describe the various lock types, starting with Shared locks. ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 14, page 774 Read Committed is highlighted because it is the Default isolation level. To achieve the Serializable isolation level, you must prevent phantoms because the transaction's behavior must be identical to what would have occurred had the transaction run on a single-user system. SQL Server provides serializability, which you can set using SET TRANSACTION ISOLATION LEVEL SERIALIZABLE. To support serializability, SQL Server locks index ranges using a special type of lock called a key-range lock. Such locks are held until the end of the transaction in order to prevent phantoms. If no index exists, the lock manager uses a table lock to guarantee serializability. With Serializable or Repeatable Read isolation, shared locks must be held until the end of the transaction to guarantee that the data that was read will not change or that new rows meeting the criteria of the query cannot be added while the transaction is in progress. For a lower isolation level, such as Committed Read, locks can be released sooner—when the use of the object is completed. For example, if a range of data is being queried in the table, there will probably be shared locks outstanding. With Committed Read isolation, a shared lock is released as soon as the scan moves off one piece of data and onto the next. Exclusive locks, on the other hand, are always held until the end of the transaction so that the transaction can be rolled back if necessary. Soporta los 4 niveles de aislamiento ANSI e ISO Seriable Lectura repetible Lectura confirmada - predeterminado Lectura no confirmada

8 Bloqueos Tipos de bloqueo en los datos del usuario - Compartidos
KEY MESSAGE: Describe shared locks SLIDE BUILDS: SLIDE SCRIPT: Shared locks are acquired automatically by SQL Server when data is read. Shared locks can be held on a table, a page, an index key, or an individual row. Many processes can hold shared locks on the same data, but no process can acquire an exclusive lock on data that has a shared lock on it (unless the process requesting the exclusive lock is the same process as the one holding the shared lock). TRANSITION: Exclusive User data lock types come next … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 14, page 780 SQL Server can lock user data resources (not system resources, which are protected with latches) at the table, page, or row level. SQL Server also locks index keys and ranges of index keys. Se adquieren automáticamente cuando se leen los datos Aplica a la Tabla, Página, Clave o fila del Índice. Varios procesos pueden mantener un bloqueo compartido en los mismos datos. No se puede bloquear exclusivamente mientras está en modo de bloqueo compartido* *A menos que sea el mismo proceso que sostiene el bloqueo compartido

9 Bloqueos Tipos de bloqueo en los datos del usuario - Exclusivos
KEY MESSAGE: Describe Exclusive Locks SLIDE BUILDS: SLIDE SCRIPT: SQL Server automatically acquires exclusive locks on data when it is modified by an insert, update, or delete operation. Only one process at a time can hold an exclusive lock on a particular data resource; in fact, as you'll see when we discuss lock compatibility, no locks of any kind can be acquired by a process if another process has the requested data resource exclusively locked. Exclusive locks are held until the end of the transaction. This means that the changed data is normally not available to any other process until the current transaction commits or rolls back. Se puede utilizar with NOLOCK en el select , el cual ni genera bloqueos compartidos, ni respeta los exclusivos, leyendo los datos. Puede tener lecturas sucias si lo utiliza TRANSITION: The Update User data lock types are next … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 14, pages 780 Se adquieren automáticamente cuando se modifican los datos Sólo un proceso puede mantenerse a la vez sobre cualquier dato. Se mantiene hasta el final de una Transacción Se rechazarán todas las demás solicitudes de bloqueo por otros procesos. Se pueden utilizar ayudas de Consulta para decidir si se leen los datos asegurados

10 Bloqueos Tipos de bloqueo en los datos del usuario - Actualización
KEY MESSAGE: What is the Update user data lock type? SLIDE BUILDS: SLIDE SCRIPT: Update locks are really not a separate kind of lock; they are a hybrid between shared and exclusive locks. They are acquired when SQL Server executes a data modification operation but first needs to search the table to find the resource that will be modified. Update locks provide compatibility with other current readers of data, allowing the process to later modify data with the assurance that the data hasn't been changed since it was last read. An update lock is not sufficient to allow you to change the data—all modifications require that the data resource being modified have an exclusive lock. An update lock acts as a serialization gate to queue future requests for the exclusive lock. (Many processes can hold shared locks for a resource, but only one process can hold an update lock.) As long as a process holds an update lock on a resource, no other process can acquire an update lock or an exclusive lock for that resource; instead, another process requesting an update or exclusive lock for the same resource must wait. TRANSITION: Next, I will Describe Intent locks … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 14, pages The process holding the update lock can acquire an exclusive lock on that resource because the update lock prevents lock incompatibility with any other processes. You can think of update locks as "intent-to-update" locks, which is essentially the role they perform. Used alone, update locks are insufficient for updating data—an exclusive lock is still required for actual data modification. Serializing access for the exclusive lock lets you avoid conversion deadlocks. Don't let the name fool you: update locks are not just for update operations. SQL Server uses update locks for any data modification operation that requires a search for the data prior to the actual modification. Such operations include qualified updates and deletes, as well as inserts into a table with a clustered index. In the latter case, SQL Server must first search the data (using the clustered index) to find the correct position at which to insert the new row. While SQL Server is only searching, it uses update locks to protect the data; only after it has found the correct location and begins inserting does it escalate the update lock to an exclusive lock. Un híbrido de compartidos y exclusivos Se adquieren cuando se requiere una búsqueda antes de cualquier modificación a los datos Permite que otros sigan leyendo mientras se aplica el bloqueo Necesita un bloqueo exclusivo para modificar los datos Los datos pueden tener varios bloqueos compartidos pero sólo un bloqueo de actualización

11 Bloqueos Tipos de bloqueo en los datos del usuario - Intentos
KEY MESSAGE: Describe Intent locks SLIDE BUILDS: SLIDE SCRIPT: Intent locks are not really a separate mode of locking; they are a qualifier to the modes previously discussed. In other words, you can have intent shared locks, intent exclusive locks, and even intent update locks. Because SQL Server can acquire locks at different levels of granularity, a mechanism is needed to indicate that a component of a resource is already locked. For example, if one process tries to lock a table, SQL Server needs a way to determine whether a row (or a page) of that table is already locked. Intent locks serve this purpose. TRANSITION: The final lock types are Special lockmodes ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 14, pages 781 No es un modo de bloqueo real, sólo un calificador, es decir, Intento de bloqueo de actualización Es utilizado por SQL como un indicador de bloqueo de recursos Muestra si un subcomponente esta bloqueado (Por ejemplo si una fila se esta actualizando (exclusivo) muestra un Intento de Exclusivo sobre la tabla)

12 Bloqueos Tipos de bloqueo en los datos del usuario - Especial
KEY MESSAGE: Describe Special lockmodes SLIDE BUILDS: SLIDE SCRIPT: SQL Server offers three additional lock modes: schema stability locks, schema modification locks, and bulk update locks. When queries are compiled, schema stability locks prevent other processes from acquiring schema modification locks, which are taken when a table's structure is being modified. A bulk update lock is acquired when the BULK INSERT command is executed or when the bcp utility is run to load data into a table. TRANSITION: Next, we’ll see how to view lock information … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 14, pages In addition, the copy operation must request this special lock by using the TABLOCK hint. Alternatively, the table can set the table option called table lock on bulk load to true, and then any bulk copy IN or BULK INSERT operation will automatically request a bulk update lock. If multiple connections have requested and received a bulk update lock, they can perform parallel loads into the same table. 3 modos especiales Estabilidad del esquema – se utiliza cuando las consultas se modifican, evita los bloqueos de “Modificación al esquema” Modificación del esquema – se utiliza cuando se modifican las estructuras de la tabla Modificación Masiva– se utiliza con el comando BULK INSERT o BCP.

13 Bloqueos Ver información del bloqueo - Tipo
KEY MESSAGE: This table shows lock types SLIDE BUILDS: SLIDE SCRIPT: This table provides information on the various lock types, which resources are being locked and the internal codes which are used to represent them. For instance, a table lock has an internal code of 5. There is also a description for lock types. The page lock can be described by a file number and a page number, while a row lock has a file, page and slot number. TRANSITION: Next, we’ll look at lock modes, abbreviations and internal codes ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 14, pages Abrev Recurso Código interno Descripción / ejemplo DB Base de datos 2 TAB Tabla 5 ID de la tabla EXT Extensión 8 Número de archivo / página 1:96 PAG Página 6 Número de archivo / página 1:104 KEY Clave 7 Valor controlado ac0001a10a00 AC Fila 9 Número de archivo / página / ranura 1:151:4 APP Aplicación 10 Control del nombre de la aplicación MYpr8dea

14 Bloqueos Ver información del bloqueo - Modo
KEY MESSAGE: lock modes, abbreviations, internal codes SLIDE BUILDS: SLIDE SCRIPT: The sp_lock and sp_lock2 procedures only display the abbreviation of lock modes. This table displays the various lock modes and the internal codes that correspond with the abbreviations. TRANSITION: Let’s look at the internal locking architecture … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 14, pages Abreviación Modo Código interno S Compartido 4 X Exclusivo 6 U Actualizar 5 IS Intento compartido 7 IU Intento actualización 8 IX Intento Exclusivo 9 SIX Compartido con Intento exclusivo 11 Sch-S Estabilidad del esquema 2 Sch-M Modificación al esquema 3 BU Actualización masiva 13

15 Arquitectura de bloqueos
Tabla de control del bloqueo Bloque de bloqueo Bloque de recurso del bloqueo Obtener Esperar Convertir Bloque de bloqueo KEY MESSAGE: Describe internal locking architecture SLIDE BUILDS: SLIDE SCRIPT: Locks are not “on-disk” structures—you won't find a lock field directly on a data page or a table header—it would be too slow to do disk I/O for locking operations. Locks are internal memory structures—they consume part of the memory used for SQL Server. Each locked data resource (a row, index key, page, or table) requires 64 bytes of memory to keep track of the database, the type of lock, and the information describing the locked resource. Each process holding a lock also must have a lock owner block of 32 bytes. A lock owner block represents a process that has been granted a lock, is waiting for the lock, or is in the process of converting to the lock. A single transaction can have multiple lock owner blocks. Also, one lock can have many lock owner blocks, as in the case with a shared lock. Finally, each process waiting for a lock has a lock waiter block of another 32 bytes. The lock manager maintains a lock hash table. Lock resources, contained within a lock block, are hashed to determine a target hash slot in the hash table. All lock blocks that hash to the same slot are chained together from one entry in the hash table. TRANSITION: Now that we have seen what a lock consumes in memory we can look at cost of row versus page level locking … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 14, pages Bloque de recurso del bloqueo Convertir Obtener Esperar Bloque dueño del bloqueo Bloque dueño del bloqueo Bloque dueño del bloqueo Todos los bloqueos propietarios de la misma transacción se enlazan entre si

16 Bloqueos Fila contra nivel de página
KEY MESSAGE: bloqueos – Row versus Page level cost SLIDE BUILDS: SLIDE SCRIPT: Considerable resources are required to manage locks. Recall that a lock is an in-memory structure of about 32 bytes, with another 32 bytes for each process holding the lock and each process waiting for the lock. If you need a lock for every row and you scan a million rows, you need more than 30 MB of RAM just to hold locks for that one process. Each page lock on the other hand will lock 8k of data, while a row may be much smaller than the 8k held by a page lock. Since the row level lock is dependent on row size which to use really depends on the application. TRANSITION: Next will be a demo, of viewing lock information … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 14, pages Beyond the memory consumption issues, locking is a fairly processing-intensive operation. Managing locks requires substantial bookkeeping. Recall that, internally, SQL Server uses a lightweight mutex called a spinlock to guard resources, and it uses latches—also lighter than full-blown locks—to protect non-leaf-level index pages. These performance optimizations avoid the overhead of full locking. The stored procedure sp_indexoption lets you manually control the unit of locking within an index. It also lets you disallow page locks or row locks within an index. Since these options are available only for indexes, there is no way to control the locking within the data pages of a heap. (But remember that if a table has a clustered index, the data pages are part of the index and are affected by the sp_indexoption setting.) The index options are set for each table or index individually. Two options, AllowRowLocks and AllowPageLocks, are both set to TRUE initially for every table and index. If both of these options are set to FALSE for a table, only full table locks are allowed. Requerimientos del bloqueo Cada bloqueo – 32 bytes Cada proceso que mantiene un bloqueo – 32 bytes Cada proceso que espera un bloqueo – 32 bytes Nivel de página – 8k Nivel de fila – depende del tamaño de la Fila Cuál utilizar depende de la aplicación

17 Demostración 1 Ver los bloqueos de SQL Server
KEY MESSAGE: Demo –View SQL Server Locks SLIDE BUILDS: None SLIDE SCRIPT: In the first demo, I will show how you can view SQL server locks. SLIDE TRANSITION: Let’s go to the demo ... ADDITIONAL INFORMATION FOR PRESENTER: Demostración 1 Ver los bloqueos de SQL Server

18 Agenda Bloqueos Procesador de consultas Ajuste de consultas
Configuración del sistema Monitoreo del rendimiento KEY MESSAGE: Agenda topic is Procesador de consultas. SLIDE BUILDS: SLIDE SCRIPT: One of the most important functions of the SQL Server engine is the query processor. Actually, there is no one component called the query processor; rather, several related components work closely together to process the queries that you or your applications submit to the SQL Server engine for processing. TRANSITION: We will now look at the first component which is Query Compilation … ADDITIONAL INFORMATION FOR PRESENTER:

19 Procesador de consultas Proceso de compilación de sentencias
KEY MESSAGE: Describe the Query Compilation Process SLIDE BUILDS: SLIDE SCRIPT: It's important to be aware that compilation and execution are distinct phases of query processing and that the gap between when SQL Server compiles a query and when the query is executed can be as short as a few microseconds or as long as several days. During the compilation process, SQL Server parses each statement and creates something called a sequence tree. This is one of the few data structures in SQL Server 2000 that has survived from SQL Server 6.5. The sequence tree is then normalized. The main function of the normalizer is to perform binding, which includes verifying that the tables and columns exist and loading the metadata for the tables and columns. Information about implicit conversions is also added to the sequence tree; for example, if the query is trying to add 10.0 to an integer value, SQL Server will insert an implicit convert into the tree. Normalization also replaces references to a view with the definition of that view. Finally, normalization includes a few syntax-based optimizations. If the statement is a DML statement(Select, Insert, Update, Delete), SQL Server extracts information from the sequence tree about that query and creates a special structure called a query graph, which is set up to let the optimizer work on it effectively. The query graph is then optimized and a plan is produced. If the statement is not a DML statement(If, Else, While, etc.), it will be compiled. These statements are not optimized. TRANSITION: Next we will look at the Optimization process in detail … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 15, pages Analizar la sentencia Crear un árbol de secuencias Normalizar el árbol Crear una gráfica de consulta ¿ Sentencia de SQL DML? No Compilar en procedimientos de sentencia de TSQL Optimizar y crear el plan Compilar en procedimientos las sentencias de TSQL

20 Procesador de Consultas Optimización de una sentencia
Optimizador de plan trivial KEY MESSAGE: Describe the Optimization process SLIDE BUILDS: SLIDE SCRIPT: The first step is called trivial plan optimization. The idea behind trivial plan optimization is that cost-based optimization is expensive to run. The trivial plan optimizer finds the really obvious plans that are typically very inexpensive. This saves the optimizer from having to consider every possible plan, which can be costly and can outweigh any benefit provided by well-optimized queries. If the trivial plan optimizer doesn't find a simple plan, SQL Server can perform some simplifications, which are usually syntactic transformations of the query itself, to look for commutative properties and operations that can be rearranged. SQL Server then loads up the metadata, including the statistical information on the indexes, and then the optimizer goes through a series of phases of cost-based optimization. Optimization is broken up into phases. Each phase is a set of rules. After each phase, SQL Server evaluates the cost of any resulting plan, and if the plan is cheap enough, it executes that plan. If the plan is not cheap enough, the optimizer runs the next phase, which is another set of rules. In the vast majority of cases, SQL Server finds a good plan in the preliminary phases. If the optimizer goes through all the preliminary phases and still hasn't found a cheap plan, it examines the cost of the best plan it has so far. If the cost is above a particular threshold, the optimizer goes into a phase called full optimization. TRANSITION: Next we will look at how the optimizer works. ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 15, pages No Si Plan encontrado? 1 Simplificación Carga de estadísticas Costo de plan mas barato > que umbral de paralelismo? Si Optimización completa para ejecución en paralelo Optimizador basado en costo: Fases 1 a n-1 No Optimización completa para ejecución en serie Encontrado plan barato? No 1 Plan de salida Si

21 Procesador de consultas Cómo funciona el optimizador
KEY MESSAGE: Describe how the optimizer works SLIDE BUILDS: SLIDE SCRIPT: The query optimizer has three main steps: First it performs a query analysis for each table involved in the query and evaluates the search conditions in the WHERE clause Next it considers which indexes are available to narrow the scan of a table. That is, the optimizer evaluates to what extent an index can exclude rows from consideration. The more rows that can be excluded, the better, because that leaves fewer rows to process. Finally, it considers Joins. Joins can be processed by one of three methods: nested iteration, hashing, or merging. For any of these methods, the optimizer decides on the order in which the tables should be accessed. TRANSITION: Once the plan is created it moves to the next query process component; Costing and caching the plan … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 15, pages Because a nested iteration is a loop, order is important. The fewer the iterations through the loops, the less processing will be required. So it is useful to start with the table (or tables) that can exclude the most rows as the outer loops. The general strategy is to have the outer table limit the search the most, which results in the fewest total iterations (scans). For each combination of join strategy, join order, and indexes, the query optimizer estimates a cost, taking into account the number of logical reads and the memory resources that are required and available. Then the optimizer compares the cost of each plan and chooses the plan with the lowest estimate. Análisis de consultas Selección de índices Selección de combinación (join) Iteración anidada (Nested iteration) Separación (Hashing) Mezcla (Merging)

22 Procesador de consultas Memoria caché – costeo de un plan de consultas
KEY MESSAGE: SQL server develops costs for query plans SLIDE BUILDS: SLIDE SCRIPT: One of the first things SQL Server determines when processing a query is whether the query is both ad hoc and cheap to compile; if so, SQL Server won't bother caching it at all. Plans are saved in cache along with a cost factor that reflects the cost of actually creating the plan by compiling the query. If the plan is ad hoc, SQL Server will set its cost to 0. The value 0 means that the plan is immediately available to be kicked out of the procedure cache. You're taking a chance that the plan might be reused, but the probability is low. If there's memory pressure on the system, plans for ad hoc statements should be the first to go. If the plan is not ad hoc, SQL Server sets the cost to the actual cost of compiling the query. These costs are basically in units of disk I/O. When a data page is read off the disk, it has a cost of 1 I/O. When this plan was built, information was read off the disk, including statistics and the text of the query itself. SQL did additional processing and that processing work is normalized to the cost of an I/O. Once the cost is computed, the plan is put into the cache. TRANSITION: We now will look further into Compilation … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 15, pages If another query comes along that can reuse that plan, SQL Server again determines what type of plan it is. If it's an ad hoc plan, SQL Server increments the cost by 1. So if ad hoc plans are really being reused, they'll stay in the cache for a little while longer as their cost factor increases. If the plan is reused frequently, the cost will keep getting bumped up by 1 until it reaches its actual creation cost—and that's as high as it will ever be set. But if it's reused a lot—if the same user or other users keep resubmitting the exact same SQL text—the plan will remain in cache. ¿Ad hoc y barato de compilar? Sin caché No Ubicar memoria del caché del búfer Ad-hoc ¿Tipo de plan? Establecer el costo inicial en cero Establecer el costo inicial al costo de creación Colocar el plan en caché

23 Procesador de consultas Flujo de Compilación Y Ejecución
KEY MESSAGE: Query compilation and execution flow SLIDE BUILDS: SLIDE SCRIPT: The end product of the compilation phase of query processing is a query plan, which, with some exceptions, is put into the procedure cache. Unless it is adhoc -- it's not a good idea to flood the cache with plans that are unlikely to be reused --ad hoc SQL is unlikely to be reused, so there is little to be gained by storing the plan in the cache. If a plan is not in cache initially, we must create one. This is shown on the left side of the flowchart. You can also see that after the plan has been put in cache, when it's time to execute it, SQL Server checks to see whether anything has changed and whether the plan must be recompiled. Even though it could be only microseconds separating compilation from execution, somebody could have executed a Data Definition Language (DDL) statement that added an index to a crucial table. This is unlikely, but SQL Server must account for it. Stored procedures are the most cost-effective mechanism for executing SQL commands from your applications, and should be used whenever possible rather than passing ad hoc SQL statements from your applications, as they do not require compilation of an execution plan for each execution. TRANSITION: Next we will have a demonstration of the Query Analyzer. ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 15, pages No Plan en Cache? Si Recuperar plan desde cache Interpretar/normalizar Si El Plan necesita recompilación? Compilar TSQL No Optimizar sentencias Esperar que el planificador de memoria autorice Poner plan en cache Abrir (activar) plan Ejecutar el plan hasta el final

24 Demostración 2 Analizador de consultas
KEY MESSAGE: demo of Query Analyzer SLIDE BUILDS: None SLIDE SCRIPT: Now we will see a demo of the Query Analyzer – we will show how to obtain statistics, use the graphical showplan, and use the estimated showplan. SLIDE TRANSITION: Now let’s go to the demo … ADDITIONAL INFORMATION FOR PRESENTER: Demostración 2 Analizador de consultas Obtener estadísticas sobre una consulta Utilizar el plan gráfico Utilizar el plan estimado

25 Agenda Bloqueos Procesador de consultas Ajuste de consultas
Configuración del sistema Monitoreo del rendimiento KEY MESSAGE: current topic is Ajuste de consultas SLIDE BUILDS: SLIDE SCRIPT: We have covered bloqueos, and the Procesador de consultas – we will now move to Ajuste de consultas … TRANSITION: and the first thing to know about Tuning is when to start … ADDITIONAL INFORMATION FOR PRESENTER:

26 Ajuste de consultas Ajuste – Cuándo empezar
KEY MESSAGE: Tuning should start early SLIDE BUILDS: SLIDE SCRIPT: If you want to end up with a poorly performing application or a complete project failure, you should wait until the end of the project to deal with performance concerns. You should start tuning from the beginning. You should consider performance before you even write your first line of code. This is the best time to try to understand what the customer is going to try to do, and to make sure that their needs are supported. Be sure that you've set up a good database structure with appropriate normalization, field widths, and data types. Review it with others to be sure that you don’t miss something obvious. Create what appear to be useful indexes, based upon the query activity that you can forecast. Your forecast may not be completely accurate, but if it is based on your experience, and your knowledge of your customer set, it will be helpful. Make sure all analysis is done with a representative workload. Understand what you can of the queries, and volumes that are typical for the intended customers. The big gains in query performance usually do not come from syntactic changes in the query but rather from a change in the database design or in indexing. TRANSITION: Now let’s look at what you can do with the Application and Database design ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 16, pages Empiece al principio Considere el rendimiento antes de que escriba su primer línea de código Asegúrese de haber establecido una buena estructura de base de datos Desarrolle lo que parezcan ser índices útiles Asegúrese que todo el análisis se realice con una carga de trabajo representativa

27 Ajuste de consultas Diseño de la aplicación y la base de datos
KEY MESSAGE: Application and Database design changes yield the big performance gains SLIDE BUILDS: SLIDE SCRIPT: Application and Database design changes can provide the biggest performance gains. You should put the effort in to design your application and database with performance in mind. Make sure to normalize your design and evaluate your critical transactions. You may have to back off normalization somewhat to get the performance necessary for your critical transactions. Keep all table row lengths and key lengths compact. And finally, create useful indexes. Creating useful indexes is one of the most important tasks you can do to achieve good performance. Indexes can dramatically speed up data retrieval and selection, but they are a drag on data modification because along with changes to the data, the index entries must also be maintained and those changes must be logged. Also remember you should benchmark, build a prototype, and test. There is no substitute for real experience with representative data. TRANSITION: Next we will look at creating and tuning indexes ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 16, pages A normalized database eliminates functional dependencies in the data so that updating the database is easy and efficient. But querying from that database might require a lot of joins between tables, so common sense comes into play. Think of normalization as typically being good for updating but potentially bad for querying. One thing that you should do immediately is look at your critical transactions—that is, transactions whose performance will make or break the system. Proper indexes are extremely important for getting the query performance you need. But you must face query-vs.-update tradeoffs similar to those described earlier because indexes speed up retrieval but slow down updating. Proporciona la mayor ganancia en rendimiento Normalice Evalúe sus transacciones críticas Mantenga compactas las extensiones de la fila de la tabla y las extensiones clave Cree índices útiles Evaluación comparativa, Prototipo y Prueba

28 Ajuste de consultas Creación y ajuste de índices
SQL Server KEY MESSAGE: process of managing indexes SLIDE BUILDS: SLIDE SCRIPT: This diagram displays the process of managing indexes, including creating and tuning them. The main tools in this scenario are SQL Server, SQL Profiler and the Index Tuning wizard. As the diagram shows real time queries can be captured from SQL Server by the SQL Profiler(or you could also use SQL Trace). The Profiler trace can be filtered to be restricted as needed and fed into the index tuning wizard, which evaluates the statements and develops an index tuning recommendation. You can then add the Recommended indexes. TRANSITION: SQL Server has other tools that help monitor performance as we shall see next. ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 16, pages , Query Analyzer could be utilized to review the queries before and after index creation to determine if if there were any improvements or the same transactions could be run through SQL Profiler again to see if there were any changes in CPU, DISK I/O, etc. Recomendaciones de ajuste Consultas en tiempo real Carga de trabajo (filtrada) Asistente de ajuste de índices Perfilador SQL

29 Ajuste de consultas Monitorear rendimiento de consultas
KEY MESSAGE: you can monitor query performance SLIDE BUILDS: SLIDE SCRIPT: Before you think about taking some action to make a query faster, such as adding an index or denormalizing, you should understand how a query is currently being processed. You should also get some baseline performance measurements so you can compare behavior both before and after making your changes. You can monitor queries with STATISTICS IO, STATISTICS TIME, and SHOWPLAN. The STATISTICS IO option provides statistics on how much work SQL Server did to process your query. When this option is set to ON, you get a separate line of output for each query in a batch that accesses any data objects. The output from SET STATISTICS IO ON includes the values Logical Reads, Physical Reads, Read Ahead Reads, and Scan Count. SET STATISTICS TIME ON is pretty self-explanatory. It shows the elapsed and CPU time required to process the query. Finally SHOWPLAN shows some basic information about how the query will be processed. The output will tell you, for each table in the query, whether indexes are being used or whether a table scan is necessary. It will also tell you the order that all the different operations of the plan are to be carried out. Query Analyzer Provides a graphical version of showplan. TRANSITION: SQL Server performs locking and query optimization automatically. But because the query optimizer is probability based, it sometimes makes wrong predictions. To manually correct these errors you can use Query Hints , which we will cover next … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 16, pages STATISTICS – Input/Output Lecturas lógicas Lecturas físicas Lecturas avanzadas de lectura Cuenta de exploración STATISTICS - Time SHOWPLAN Showplan_Text, Showplan_All, Graphical Showplan

30 Ajuste de consultas Sugerencias de consulta
KEY MESSAGE: use Query Hints for special cases SLIDE BUILDS: SLIDE SCRIPT: You can use Query Hints to specify behaviors different from those in effect. Query hints should be used for special cases—not as standard operating procedure. When you specify a hint, you constrain SQL Server. For example, if you indicate in a hint that a specific index should be used and later you add another index that would be even more useful, the hint prevents the query optimizer from considering the new index. There are four general types of hints. First, Join hints which specify the join technique that will be used. (Hash Join, Loop Join, Merge Join, Remote) Second, Index hints which specify one or more specific indexes that should be used to drive a search or a sort. Third, Lock hints which specify a particular locking mode that should be used. Finally, Processing hints which specify that a particular processing strategy should be used. There are 8 different types of processing hints TRANSITION: Our next query topic is Blocking and Deadlocks … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 16, pages Las sugerencias de consulta se deben utilizar para casos especiales – no como un procedimiento operativo estándar Tipos de consulta: Sugerencias de unión Sugerencias de índices Sugerencias de bloqueos Sugerencias de procesamientos

31 Ajuste de consultas Bloqueos e Interbloqueos – Cómo resolverlos
KEY MESSAGE: you can reduce blocking and deadlocks SLIDE BUILDS: SLIDE SCRIPT: A process blocks when it stalls while waiting to acquire a lock that is incompatible with a lock held by some other process. This condition is often, but erroneously, referred to as a "deadlock." As long as the process being stalled is not, in turn, stalling the offending process you have a blocking problem, not a deadlock. Some things you can do to keep from getting into a blocking situation are Keep transactions as short as possible. The shorter the duration of the transaction, the shorter the time that locks will be held. Never add a pause within a transaction for user input. When you process a result set, process all rows as quickly as possible. For browsing applications, consider using cursors with optimistic concurrency control. An address book application is a good example of a browsing application: users scroll around to look at data and occasionally update it. But the update activity is relatively infrequent compared to the time spent perusing the data. Using scrollable cursors with the OPTIMISTIC locking mode is a good solution for such applications. Instead of locking, the cursor's optimistic concurrency logic determines whether the row has changed from the copy that your cursor read. If the row has not changed during the lengthy period in which the user is perusing the data, the update is made without holding locks. If the row has changed, the UPDATE statement produces an error and the application can decide how to respond. TRANSITION: Next, Resolving Deadlocks … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 16, pages Mantenga las transacciones lo más cortas posibles Nunca agregue una pausa dentro de una transacción para entradas del usuario Cuando procesa un conjunto de resultados, procese todas las filas tan pronto como sea posible Para aplicaciones de scrolling de registros, considere utilizar cursores con control de concurrencia optimista

32 Ajuste de consultas interbloqueos – Cómo resolverlos
KEY MESSAGE: you can resolve deadlocks SLIDE BUILDS: SLIDE SCRIPT: Deadlocks befuddle many programmers and are the bane of many applications. A deadlock occurs when, without some intervening action, processes cannot get the locks they need no matter how long they wait. Simply waiting for locks is not a deadlock condition. SQL Server automatically detects the deadlock condition and terminates one of the processes to resolve the situation. There are two general forms of deadlocks; cycle deadlocks and conversion deadlocks. Deadlocks can usually be avoided, although you might have to do some detailed analysis to solve the problems that cause them. Sometimes the cure is worse than the ailment, and you're better off handling deadlocks rather than totally preventing them. Preventing deadlocks (especially conversion deadlocks) requires a thorough understanding of lock compatibility. The main techniques you can use to prevent deadlocks: To prevent cycle deadlocks, make all processes access resources in a consistent order. Reduce the transaction isolation level if it's suitable for the application. To prevent conversion deadlocks, explicitly serialize access to a resource. TRANSITION: Performance tuning requires a step-by-step approach … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 16, pages Para evitar interbloqueos en los ciclos, haga que los procesos accedan a los recursos en un orden consistente. Reduzca el nivel de aislamiento de la transacción si es posible para la aplicación. Para evitar interbloqueos de conversión, serialice explícitamente el acceso a un recurso.

33 Ajuste de consultas Ajuste de rendimiento
Un enfoque paso por paso KEY MESSAGE: step-by-step approach SLIDE BUILDS: You should take a step-by-step approach to performance tuning … first [BUILD1] Gather information about the application’s behavior Possibly use SQL Profiler to gather information [BUILD2]Next, you should Analyze the information, using the Query Analyzer and then use the Index Tuning Wizard to identify needed indexes [BUILD3]And finally, Apply Changes recommended by the Index Tuning Wizard .. SLIDE SCRIPT: SLIDE TRANSITION: Next, we will have a demo of the Load Simulator. ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 16, pages , , , Recopile información acerca del comportamiento de la aplicación Utilice el Perfilador SQL Analice la información Analizador de consultas Asistente de ajuste de índices Aplique cambios Administrador empresarial

34 Demostración 3 Simulador de carga
KEY MESSAGE: load simulator demo SLIDE BUILDS: None SLIDE SCRIPT: We will now demonstrate the load simulator. SLIDE TRANSITION: Let’s go to the demo … ADDITIONAL INFORMATION FOR PRESENTER: Demostración 3 Simulador de carga

35 Demostración 4 Asistente de ajuste de índices
KEY MESSAGE: demo of index tuning wizard SLIDE BUILDS: None SLIDE SCRIPT: We will now have another demo – this one, of the Index Tuning Wizard. SLIDE TRANSITION: Let’s go to the demo ... ADDITIONAL INFORMATION FOR PRESENTER: Demostración 4 Asistente de ajuste de índices Analizar la carga de trabajo Ver reportes Aplicar índices sugeridos

36 Agenda Bloqueos Procesador de consultas Ajuste de consultas
Configuración del sistema Monitoreo del rendimiento KEY MESSAGE: current agenda item: system configuration SLIDE BUILDS: SLIDE SCRIPT: A badly configured system can destroy performance. For example, a system with an incorrectly configured memory setting can break an application. SQL Server dynamically adjusts the most important configuration options for you; you should accept these defaults unless you have a good reason to change them. TRANSITION: Next we will look at system and SQL configuration ADDITIONAL INFORMATION FOR PRESENTER:

37 Configuración del sistema Asignación de recursos y ubicación de los archivos del sistema
KEY MESSAGE: system configuration affects SQL Server SLIDE BUILDS: SLIDE SCRIPT: A few basics of system configuration affect SQL Server greatly -- First, A computer running Windows NT Server or Windows 2000 Server for file and print services will want to use the most memory for file caching. But if it is also running SQL Server, it makes sense for more memory to be available for SQL Server's use. In Windows 2000, you can change the properties for file and print services by right-clicking on My Network Places and choosing Properties. Then right-click on Local Area Connection and again choose Properties. Select File And Printer Sharing For Microsoft Networks and click the Properties button. Second, The system page file, pagefile.sys is a hidden file that resides on the system boot C: drive. You should not store SQL Server temp files, or log files on the same drive as the system paging file. TRANSITION: Now let’s look at reconfiguring SQL resources… ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 17, pages Asegúrese de que el rendimiento de los datos maximizados para las aplicaciones de la red se seleccione para los servicios de archivo e impresión No ubique los archivos de SQL Server en la misma unidad que PAGEFILE.sys

38 Configuración del sistema Configurar los recursos de SQL
Sp_configure EXEC sp_configure RECONFIGURAR Con sobrecarga Administrador empresarial KEY MESSAGE: Configuration can improve or degrade SLIDE BUILDS: SLIDE SCRIPT: Configuration changes can degrade system performance just as easily as they can improve it. This is particularly true in version 2000 of SQL Server, for which most performance-oriented configuration settings are fully automatic. You should change configuration options only when you have a clear reason for doing so, and you should closely monitor the effects of each change to determine whether the change improved or degraded performance. Always make and monitor changes one at a time. You can change configuration options, in most cases, through the enterprise manager properties tabs, but there is no single dialog box from which all configuration settings can be seen or changed. You can also change settings by executing the stored procedure sp_configure. If you execute sp_configure without parameters it will show you a table of options. Some are listed here. If you use the sp_configure stored procedure, no changes take effect until the RECONFIGURE command (or RECONFIGURE WITH OVERRIDE, in some cases) is issued. Some changes (dynamic changes) take effect immediately upon reconfiguration, but others do not take effect until the server is restarted. If an option's run_value and config_value as displayed by sp_configure are different, you must restart the server in order for the config_value to take effect. TRANSITION: We will now look at some of the options which can affect performance. ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 17, pages

39 Configuración del sistema Configurar los recursos de SQL
KEY MESSAGE: You can set memory parameters for SQL SLIDE BUILDS: SLIDE SCRIPT: By default, SQL Server automatically adjusts the total amount of the memory resources it will use. However, you can use the min server memory and max server memory configuration options to take manual control. The default setting for min server memory is 0 (MB), and the default setting for max server memory is 2 gigabytes. You can also set the working set size by checking the box labeled Reserve Physical Memory. Setting this option means that the operating system does not swap out SQL Server pages even if they can be used more readily by another process when SQL Server is idle. The Minimum Query Memory option is the minimum memory that sort, merge and hash operations receive. You should rarely need to adjust this value. On smaller machines, setting this option too high could cause excessive paging, hurting server performance. TRANSITION: Next, we’ll look at scheduling. ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 17, pages , If you use the sp_configure stored procedure to change both of these options to the same value, you basically take full control and tell SQL Server to use a fixed memory size. This mimics the memory configuration behavior prior to SQL Server 7. You can also use SQL Server Enterprise Manager to set a minimum and maximum value for memory, using the Memory tab of the SQL Server Properties dialog box shown. To bring up the dialog box, right-click on the name of your server and then choose Properties. Memoria mínima del servidor y memoria máxima del servidor Configurar el tamaño del conjunto del trabajo Memoria de consulta mínima

40 Configuración del sistema Configurar los recursos de SQL
KEY MESSAGE: You can manage SQL Server scheduling. SLIDE BUILDS: SLIDE SCRIPT: SQL Server 2000 has a special algorithm for scheduling user processes, which uses User Mode Scheduler (UMS) threads. UMS keeps the number of users per CPU balanced. There are four options that affect the scheduler. The first is Lightweight pooling. Lightweight Pooling is when SQL Server operates in fiber mode rather than thread mode. This can yield as much as a 5 percent increase in performance on a loaded system, but running queries on linked servers or executing extended stored procedures requires thread mode and there is a cost switching from fiber to thread mode that can impact performance, in some cases offseting any gains from fiber mode. Unless your system is running at 100% CPU it probably isn’t worth considering. The second option is the Affinity Mask which binds all the threads (or fibers) handled by one UMS thread to a certain processor. This is generally not desirable, because it prevents the operating system from using whatever processor is currently most available. You can also use the affinity mask setting to limit the number of processors that SQL Server can use. The third option is the priority boost setting. When enabled, SQL Server runs at a higher scheduling priority. The default is 0, normal priority. This option will likely not make much difference in performance, but on a dedicated SQL Server box, you might want to enable this option (set it to 1) to see for yourself. The last option is max worker threads. This setting defaults to It refers to the number of worker threads (or fibers) that take requests off the queue. It attempts to evenly divide the worker threads among the UMS schedulers. SQL Server handles disk read behavior internally and options cannot be set in this version, but one option is available to control disk write behavior, the recovery interval. It controls how frequently the checkpoint process writes to disk. This should be left at default 0 which means less than one minute, except in special cases. TRANSITION: Now, let’s look at managing query processing configuration ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 17, pages Programar Agrupamiento de peso ligero Máscara de afinidad Inicio de prioridad Hilos máximos para el trabajador Opciones E/S del disco Intervalo de recuperación

41 Configuración del sistema Configurar los recursos de SQL
KEY MESSAGE: query processing configuration SLIDE BUILDS: SLIDE SCRIPT: You can control the resources available to SQL Server for processing queries, but it is best to leave these options at their default values unless thorough testing indicates that a change might help. The Min Memory Per Query is the least amount of memory that a sort, merge join or hash join operation receives. It does not apply to the sorting that takes place during index creation. That is determined by the index create memory which allocates memory for index creation. The query wait sets how long a query will wait for memory if none is available. The Query governor cost limit sets a maximum length of time that a query will run, and the Max degree of parallelism option indicates the maximum number of processors that are used to run queries in parallel. The default value of 0 means that SQL Server should use all CPUs and 1 means that SQL Server should suppress parallelism completely. TRANSITION: Next, database options that affect performance … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 17, pages Be careful when you use the max degree of parallelism or cost threshold for parallelism options—they have server wide impact. You can also use trace flag 8687 to turn off parallelism for individual connections. Opciones de procesamiento de consultas Memoria mínima por consulta Memoria para crear índices Espera de consulta Límite de costo de gobernador de consulta Máximo grado de paralelismo

42 Configuración del sistema Configurar los recursos de SQL
KEY MESSAGE: database options affect performance SLIDE BUILDS: SLIDE SCRIPT: Several database options affect performance. The read only and single user options eliminate locking in some cases. You may set the database to read only for a decision support system. The single user option can be enabled to perform off-hour maintenance tasks and bulk loading operations ensuring that only one user is on the system during these resource intensive tasks. Autoclose and autoshrink options are useful if you're running SQL Server Desktop Edition on a small machine and your resources are extremely limited. The autoclose option causes the database to shut down cleanly and free resources after the last user exits. The autoshrink option can be helpful if your disk space resources are extremely limited, but you have spare CPU time. Shrinking a database is CPU-intensive. Finally, two database options control automatic gathering of statistics: auto create statistics and auto update statistics. TRANSITION: And finally, the Buffer Manager … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 17, pages Opciones de la base de datos Sólo lectura Usuario único Autocierre Autoreducción Creación automática de estadísticas Actualización automática de estadísticas

43 Configuración del sistema Configurar los recursos de SQL
KEY MESSAGE: You can “pin” tables in memory SLIDE BUILDS: SLIDE SCRIPT: The buffer manager manages Disk I/O functions for bringing data and index pages into the buffer pool so that data can be shared among users. Setting the pintable option will override the buffer manager and hold specified tables in memory. The pintable option is not appropriate for most sites. But if you get very random cache hits and you have some relatively small tables that are hot compared to other larger tables, this option might be beneficial. If those small, hot tables keep getting forced out by the random access to larger tables and you have plenty of memory, you can pin those small tables. This will remove a table from the queue of pages examined by the lazywriter so that once they are read into the data cache, they are never forced from cache. You can enable this option using the sp_tableoption stored procedure with the pintable option. There are two DBCC commands that exist to monitor the performance of the buffer manager; they are known as SQLPERF(WAITSTATS) and SQLPERF(LRUSTATS). DBCC SQLPERF(WAITSTATS) not only provides an overview of the buffer manager, it also helps identify where a transaction is delayed. It shows the total wait time and how much of the time is due to waiting for reads, waiting for different types of locks, waiting to add a log record to the log buffer, and waiting for log buffers to be physically written. The command DBCC SQLPERF(LRUSTATS) gives details on the lazywriter and on the state of the cache, such as the cache-hit ratio, the size of the cache, the average number of pages scanned to find an available buffer, and the number of free pages. Although this information is available through System Monitor, the DBCC SQLPERF command lets you capture the output to a table and save the data for analysis. TRANSITION: It is now time to try out some of these options in another demo … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 3, pages and Chapter 17, pages For example, to capture the DBCC SQLPERF(WAITSTATS) output, you can create a table with four columns and use the dynamic EXECUTE command to populate the table. Administrador de búfer Opción “Pintable” Monitoreo del rendimiento SQLPERF(WAITSTATS) SQLPERF(LRUSTATS)

44 KEY MESSAGE: Demo SQL Config
SLIDE BUILDS: None SLIDE SCRIPT: We will now show SQL Configuración del sistema options we just discussed, using the Enterprise Manager, and the sp_configure procedure. SLIDE TRANSITION: Let’s go to the demo … ADDITIONAL INFORMATION FOR PRESENTER: Demostración 5 Configuración del sistema SQL Administrador empresarial sp_configure

45 Agenda Bloqueos Procesador de consultas Ajuste de consultas
Configuración del sistema Monitoreo del rendimiento KEY MESSAGE: agenda– performance monitoring SLIDE BUILDS: SLIDE SCRIPT: We will now look at performance monitoring and the tools we use to tune a SQL System. TRANSITION: First we will look at the SQL Profiler tool. ADDITIONAL INFORMATION FOR PRESENTER:

46 Monitoreo del rendimiento Cómo utilizar el Perfilador de SQL
KEY MESSAGE: SLIDE BUILDS: SLIDE SCRIPT: SQL Profiler is Graphical tool that monitors and collects Microsoft® SQL Server™ 2000 events from a server. It can capture the series of SQL statements that lead to a problem and helps to identify poorly-performing queries. The events are saved in a trace file that can later be analyzed or used to replay a specific series of steps when trying to diagnose a problem. You can use SQL Profiler to monitor the behavior of your server on a query-by-query or event-by-event basis, but not the system performance as a whole. TRANSITION: Next, we’ll consider when to use the Profiler… ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 17, pages also look in Monitoring with SQL Profiler in Books Online SQL Profiler also supports auditing the actions performed on instances of SQL Server. Audits record security-related actions for later review by a security administrator. SQL Server 2000 auditing meets C2 security certification requirements. Monitoree eventos del servidor Capture instrucciones de SQL Identifique consultas con rendimiento bajo Reproduzca los problemas para su diagnóstico

47 Monitoreo del rendimiento Cuándo utilizar el Perfilador de SQL
KEY MESSAGE: When to use Profiler SLIDE BUILDS: None SLIDE SCRIPT: You can use the SQL Profiler as a troubleshooting tool for several scenarios: You can use it to Debug T-SQL or stored procedures, with step-by-step execution and tracing. You can use Profiler to Monitor the performance of SQL Server to tune workloads If your system is suffering deadlocks, SQL Profiler can Capture deadlocking scenarios And when you capture something interesting, you can Playback events which you captured. We’ll see these later in a demo. SLIDE TRANSITION: Now let’s look closer at SQL Profiler… ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 17, pages also look in Scenarios in Books Online Depurar T-SQL o procedimientos almacenados Monitorear el rendimiento de SQL Server para ajustar las cargas de trabajo Capturar los escenarios de interbloqueos Eventos de reproducción capturados

48 Monitoreo del rendimiento Perfilador SQL
KEY MESSAGE: Event categories, data columns, filters SLIDE BUILDS: SLIDE SCRIPT: SQL Profiler uses event categories to monitor events in Microsoft® SQL Server™. Event categories contain event classes that have been grouped together within the SQL Profiler user interface. SQL Profiler allows you to select data columns when you create a template. These data columns represent the information you would like returned when a trace is running. The data displayed in SQL Profiler can be displayed either in the order the events occur or in a group based on one or a combination of data columns. SQL Profiler allows you to filter the information captured by specifying criteria for determining which events to capture. TRANSITION: This will all mean more to you once we see it work, so … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 17, pages Templates - you can use SQL Profiler to create one or more templates that define the criteria for each event you want to monitor. You can save the template to a file with the .tdf extension. A template is not executed. After you define the template, you run a trace that records the data for each event you selected. Some default templates are provided with SQL Profiler that specify which events, data columns, and filters to use when running certain traces. These templates include templates for capturing Stored Procedures, TSQL, tuning, and several others. Categorías de eventos Columnas de datos Filtros

49 Demostración 6 Perfilador SQL
KEY MESSAGE: demo SQL Profiler SLIDE BUILDS: None SLIDE SCRIPT: Let’s have a demo of SQL Profiler. We’ll look at tracing queries, and the Create Trace Wizard. SLIDE TRANSITION: Let’s go to the demo … ADDITIONAL INFORMATION FOR PRESENTER: Demostración 6 Perfilador SQL Rastrear consultas en una base de datos Crear asistente de rastreo

50 Monitoreo del rendimiento Procedimientos almacenados del sistema
KEY MESSAGE: SQL Trace and SQLDIAG usage SLIDE BUILDS: SLIDE SCRIPT: Now we’re back from the demo, we’ll look at using System Stored Procedures for Monitoreo del rendimiento. SQL Trace is the server side trace that is made up of the following procedures. sp_trace_create sets up the trace and configures a file to keep the captured events. It returns a trace ID number that is then used in the other three procedures to further define and manipulate the trace. sp_trace_setevent is then called once for each data column of every event that you want to capture. sp_trace_setfilter can be called once for each filter you want to define on any of the events' data columns. sp_trace_setstatus is called to start, stop or remove the trace. A fifth procedure, sp_trace_generateevent, can optionally be called to generate user-defined events. Sqldiag When you execute sqldiag from a command prompt while SQL Server is running, it gathers information that you can provide to Microsoft for problem diagnosis and resolution. TRANSITION: Our next step will be a demo of the system diagnostic procedures. ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 17, pages SQL Trace sp_trace_create sp_trace_setevent sp_trace_setfilter sp_trace_setstatus sp_trace_generateevent SQLDIAG

51 Demostración 7 Procedimientos de diagnóstico del sistema
KEY MESSAGE: system diagnostic procedures SLIDE BUILDS: None SLIDE SCRIPT: We will now demonstrate the system diagnostic procedures, SQLTrace and SQLDIAG SLIDE TRANSITION: Let’s go to the demo … ADDITIONAL INFORMATION FOR PRESENTER: Demostración 7 Procedimientos de diagnóstico del sistema

52 Monitoreo del rendimiento Uso del monitor del sistema
Monitorea todo el rendimiento del sistema Contadores del sistema Contadores de SQL KEY MESSAGE: System Monitor to monitor entire server SLIDE BUILDS: SLIDE SCRIPT: You can use SQL Profiler to monitor the behavior of your server on a query-by-query or event-by-event basis. But if you want to monitor your server's performance as an entire system, the best tool is System Monitor. This tool is extensible, which allows SQL Server to export its performance statistics so that you can monitor your entire system. That's crucial because such important statistics as CPU use must be monitored for the entire system, not just for SQL Server. In fact, many of the most important counters to watch while performance tuning SQL Server don't even belong to any of the SQL Server objects. System Monitor provides a huge set of counters. Probably no one understands all of them, so don't be intimidated. Peruse all the objects and counters and note which ones have separate instances. Don't confuse System Monitor's use of the word "instance" with a SQL Server 2000 instance. System Monitor uses instance to refer to a particular occurrence of a counter. TRANSITION: Let’s look at more detail on the System Monitor … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 17, page 976

53 Monitoreo del rendimiento Monitor del sistema
Monitorea varias computadoras simultáneamente Ve y cambia gráficos para reflejar la actividad actual Exporta datos a hojas de cálculo o aplicaciones de la base de datos Agrega alertas al sistema para notificarle de posibles problemas KEY MESSAGE: System Monitor Capabilities SLIDE BUILDS: SLIDE SCRIPT: System monitor can view data simultaneously from any number of computers. It allows you to View and change charts to reflect current activity, and show counter values that are updated at a user-defined frequency. You can export data from charts, logs, alert logs, and reports to spreadsheet or database applications for further manipulation and printing. And you can add system alerts that list an event in the alert log which can notify you of possible problems by reverting to the Alert view or issuing a network alert. TRANSITION: Let’s look at more detail on the System Monitor capabilities … ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 17, pages 976 SQL Server 2000 Resource Kit, Chapter 14 Windows 2000 Server Operations Guide in the Windows 2000 Server Resource Kit, Chapters

54 Monitoreo del rendimiento Monitor del sistema
Ejecuta una aplicación cuando un valor del contador excede el valor definido por el usuario Desarrolla archivos de registro Anexa archivos de registro para formar un fichero a largo plazo Ve los reportes actuales de actividades Genera reportes a partir de los archivos de registro existentes Guarda gráficos, alertas, registros o configuraciones de reportes KEY MESSAGE: System Monitor Capabilities SLIDE BUILDS: SLIDE SCRIPT: Here are some of the things you can do with System Monitor: Run a predefined application the first time or every time a counter value goes over or under a user-defined value. Create log files that contain data about various objects from different computers. Append to one file selected sections from other existing log files to form a long-term archive. View current-activity reports, or create reports from existing log files. Save individual chart, alert, log, or report settings, or the entire workspace setup for reuse when needed. TRANSITION: Next we will review just a few counters, but there are dozens of others, for monitoring almost every aspect of SQL Server behavior. ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 17, pages 976 SQL Server 2000 Resource Kit, Chapter 14 Windows 2000 Server Operations Guide in the Windows 2000 Server Resource Kit, Chapters

55 Monitoreo del rendimiento Monitor del sistema – Contadores del sistema
KEY MESSAGE: System Monitor - Counters SLIDE BUILDS: SLIDE SCRIPT: Here are some of the counters in System Monitor that are useful for SQL Server monitoring: The number of times per second that the processor switches among threads is called context switches. If this counter shows a lot of switching on a heavily loaded system with at least 4 processors you may benefit by switching to fibers. The %processor Time counter monitors the amount of time the processor spends processing non-idle threads. If you use multiple processors, you can set up an instance for each processor. This counter should be < 85% on average. The %Privileged Time counter monitors the percentage of time the processor spends in privileged time, executing Windows 2000 operating system kernel commands such as processing SQL Server I/O requests and the %User Time monitors the percentage of time that the processor spends executing user processes such as SQL Server. You can use these counters with %Processor Time to gain more detail information on processor activity. Finally the %Processor Queue Length monitors the number of threads waiting. A queue length of two or more items indicates that a processor bottleneck exists. TRANSITION: Next we will review a few more counters, for monitoring SQL Server behavior. ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 17, pages SQL Server 2000 Resource Kit, Chapter 26 – System Performance Counters Books OnLine, Under System Monitor – Counters Windows 2000 Help - Processor counters under Performance counters Sistema: Cambios/seg del contexto Procesador: Tiempo de %Processor Tiempo de %Privileged Tiempo de %User Extensión de la consulta del procesador

56 Monitoreo del rendimiento Monitor del sistema – Contadores del sistema
KEY MESSAGE: More System Monitor Counters SLIDE BUILDS: SLIDE SCRIPT: Here are more counters that can prove useful for SQL Server. The SQL Server: Memory Manager: Total Server Memory(KB) counter shows memory allocated in the SQL Server buffer pool, but it is important to note that it doesn't reflect all memory allocated within a SQL Server process space. The Process: Working Set Counter For SQL Server Instance is the current memory that SQL Server (and any components loaded in it) is currently accessing. It may not reflect the total memory allocated or committed to SQL Server, but as long as no trimming has occurred, Working Set is the best counter to assess SQL memory usage. The SQL Server Buffer Manager: Buffer Cache Hit Ratio is the ratio of how often data is found in the buffer cache as opposed to having to be read in. Ideally you want to achieve rates of 90 percent or higher, but this is not always possible if the I/O is random. TRANSITION: There are a few more System Monitor counters useful in monitoring SQL Server. ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 17, pages SQL Server 2000 Resource Kit, Chapter 26 – System Performance Counters Books OnLine, Under System Monitor - Counters SQL Server: Administrador de memoria: Memoria total del servidor (KB) Proceso: Contador del conjunto de trabajo para la instancia de SQL Server Administrador del búfer de SQL Server: Coeficiente de la memoria caché del búfer

57 Monitoreo del rendimiento Monitor del sistema – Contadores del sistema
KEY MESSAGE: more counters SLIDE BUILDS: SLIDE SCRIPT: The Memory: Pages/sec counter watches the amount of paging on the system. As the system settles into a steady state, you want its value to be 0, ie. no paging. Also the SQL Server: Databases: Transactions/sec counter measures actual transactions—either user-defined transactions surrounded by BEGIN TRAN and COMMIT TRAN or individual data modification statements if no BEGIN TRAN has been issued. Use it only as a general indication of your system throughput. There is no "correct" value—just the higher the better. The last counter we will discuss here is the PhysicalDisk:Disk Transfers/sec counter. This counter shows physical I/O rates for all activity on the machine. You can set up an instance for each physical disk in the system or watch it for the total of all disks. TRANSITION: Now that we’ve looked at System Monitor, and some of the many counters, let’s try a demo of System Monitor …. ADDITIONAL INFORMATION FOR PRESENTER: Inside SQL Server 2000, Chapter 17, pages SQL Server 2000 Resource Kit, Chapter 26 – System Performance Counters Books OnLine, Under System Monitor - Counters %Disk time Current Disk Queue Length This counter indicates the number of reads that are currently outstanding for a disk. The disks should not have a lot of queued I/O. Avg. Disk Queue Length Disk reads/sec Disk writes/sec Memoria: Páginas/seg SQLServer: Bases de datos Transacciones/seg Disco físico: Transferencias/seg del disco

58 Demostración 8 Monitor del sistema
KEY MESSAGE: Demo System Monitor SLIDE BUILDS: None SLIDE SCRIPT: Now we will demo System Monitor setup for use with SQL Server … SLIDE TRANSITION: Let’s go to the demo … ADDITIONAL INFORMATION FOR PRESENTER: Demostración 8 Monitor del sistema Configurar monitor del sistema

59 Resumen de la sesión SQL Server 2000 puede utilizar varias técnicas para mejorar el rendimiento de las aplicaciones Las técnicas incluyen: Diseño de la aplicación y de la base de datos Ajuste de consultas Configuración del sistema Monitoreo del rendimiento KEY MESSAGE: manage SQL Server performance SLIDE BUILDS: None SLIDE SCRIPT: As we have seen today, there are many tools and techniques that you can apply to SQL Server 2000 installations and applications to enhance performance. Some of Techniques we have covered today include: Application and Database design – probably the area for biggest gains Ajuste de consultas – a process that should begin early in the application lifecycle Configuración del sistema – choice of key options can affect performance dramatically Monitoreo del rendimiento – to define the problems, and afterwards to validate the solution So I hope that you take with you today a better understanding of the wide range of tools and techniques available for SQL Server Performance. SLIDE TRANSITION: Now, where should you go for more information? ADDITIONAL INFORMATION FOR PRESENTER:

60 Para mayores informes…
Sitio Web TechNet en Microsoft Official Curricula (MOC) Curso # 2071 – Consultas de Microsoft SQL Server 2000 con Transact-SQL Curso # 2072 – Administrar una base de datos Microsoft SQL Server 2000 Microsoft Press “Inside SQL Server 2000”, Microsoft Press, 2000., o: “Microsoft® SQL Server™ 2000 Resource Kit”, “Microsoft® SQL Server™ 2000 Reference Library “, “Microsoft® SQL Server™ 2000 Administrator's Companion”, “Microsoft® BackOffice® 4.5 Resource Kit ”, Microsoft Press, 1999, o: KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: This slide shows a number of different data sources for information on SQL Server 2000, including resources on the Web, and in print. SLIDE TRANSITION: Next, let’s look at some important training courses … ADDITIONAL INFORMATION FOR PRESENTER:

61 Capacitación Recursos de capacitación para los profesionales de informática
KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: This slide shows training on SQL Server 2000 offered by Microsoft CTECs. SLIDE TRANSITION: Next, let’s look at getting more out of TechNet … ADDITIONAL INFORMATION FOR PRESENTER: Please be sure to tell the audience that these Training courses are related to the subject that we just covered in the slides, but they do not necessarily provide in-depth coverage of this exact subject. Anyone interested in the courses should visit the MSDN Training Web site at msdn.microsoft.com/training and review the syllabus of any course that they are interested in taking. Consultas de Microsoft SQL Server 2000 con Transact-SQL Curso # 2071 — Dos días — Dirigido por instructor o aprendizaje por correo electrónico Disponible: a través de MS CTECs en su área Administrar una base de datos Microsoft SQL Server 2000 Curso # 2072— Cinco días — Dirigido por instructor Para localizar al proveedor de capacitación para este curso, visite mcspreferral.microsoft.com/default.asp Microsoft Certified Technical Education Centers (CTECs) son socios premier de Microsoft para servicios de capacitación

62 ¿Dónde puedo obtener TechNet?
Visite TechNet Online en Regístrese para TechNet Flash Únase al foro TechNet Online en Conviértase en un suscriptor de TechNet en technetbuynow.one.microsoft.com Asista a más eventos TechNet KEY MESSAGE: how to be a part of TechNet. SLIDE BUILDS: None SLIDE SCRIPT: There is one place you should go to start: There is one communication you should subscribe to: TechNet Flash. Twice monthly for the IT Pro community - focuses on news, information, resources and events. Post questions on the discussion forum. Subscribe online Look for TechNet branded events - feature SLIDE TRANSISTION: You should also consider certification … ADDITIONAL INFORMATION FOR PRESENTER:

63 Conviértase en un Microsoft Certified Systems Engineer
KEY MESSAGE: Explain the MCSE program SLIDE BUILDS: None SLIDE SCRIPT: The Microsoft® Certified Systems Engineer credential is the premier certification for professionals who analyze the business requirements and design and implement the infrastructure for business solutions based on the Microsoft Windows® 2000 platform and Microsoft server software. Implementation responsibilities include installing, configuring, and troubleshooting network systems. For more information about the MCSE certification, please visit: SLIDE TRANSITION: Finally, a word from our sponsor, and the fine folks who brought you this seminar today… ADDITIONAL INFORMATION FOR PRESENTER: ¿Qué es MCSE? Certificación Premier para profesionales que analizan los requerimientos de negocios y diseñan e implementan la infraestructura para soluciones de negocios con base en el software del servidor Microsoft. ¿Cómo me puedo convertir en un Windows 2000 MCSE? Pasar 4 exámenes básicos Pasar 1 examen de diseño Pasar 2 exámenes opcionales a partir de una lista completa ¿Dónde obtengo mayores informes? Para mayores informes acerca de los requerimientos, exámenes y opciones de capacitación para la certificación, visite

64 KEY MESSAGE: WDYWTGT SLIDE BUILDS: None SLIDE SCRIPT: SLIDE TRANSITION: ADDITIONAL INFORMATION FOR PRESENTER:

65 USE master GO CREATE procedure sp_lock2 @spid1 int = NULL, /* id del proceso de servidor para el que se comprueban los bloqueos */ @spid2 int = NULL /* otros id de proceso para el que comprobar los bloqueos */ as set nocount on /* ** Muestra los bloqueos para ambos parámetros. ** No muestra los bloqueos de master, tempdb, model o msdb */ is not NULL begin select convert (smallint, req_spid) As spid, convert(char(20),db_name(rsc_dbid)) As [Database], rsc_objid As ObjId, rsc_indid As IndId, substring (v.name, 1, 4) As Type, substring (rsc_text, 1, 16) as Resource, substring (u.name, 1, 8) As Mode, substring (x.name, 1, 5) As Status from master.dbo.syslockinfo, master.dbo.spt_values v, master.dbo.spt_values x, master.dbo.spt_values u where master.dbo.syslockinfo.rsc_type = v.number and v.type = 'LR' and master.dbo.syslockinfo.req_status = x.number and x.type = 'LS' and master.dbo.syslockinfo.req_mode + 1 = u.number and u.type = 'L' and rsc_dbid >=5

66 and req_spid in (@spid1, @spid2)
end /* ** Sin parámetros, muestra todos los bloqueos. */ else begin select convert (smallint, req_spid) As spid, convert(char(20),db_name(rsc_dbid)) As [Database], rsc_objid As ObjId, rsc_indid As IndId, substring (v.name, 1, 4) As Type, substring (rsc_text, 1, 16) as Resource, substring (u.name, 1, 8) As Mode, substring (x.name, 1, 5) As Status from master.dbo.syslockinfo, master.dbo.spt_values v, master.dbo.spt_values x, master.dbo.spt_values u where master.dbo.syslockinfo.rsc_type = v.number and v.type = 'LR' and master.dbo.syslockinfo.req_status = x.number and x.type = 'LS' and master.dbo.syslockinfo.req_mode + 1 = u.number and u.type = 'L' and rsc_dbid >=5 order by spid return (0) -- sp_lock2


Descargar ppt "Rendimiento de Microsoft® SQL Server TM 2000"

Presentaciones similares


Anuncios Google