---从计划缓存中直接获取查询计划和参数: DECLARE @dbname NVARCHAR(256), @procname NVARCHAR(256) SELECT @dbname = 'hydee_连锁', @procname = 'dbo.p_select_ware'; WITH basedata AS ( SELECT qs.statement_start_offset / 2 AS stmt_start, qs.statement_end_offset / 2 AS stmt_end, est.encrypted AS isencrypted, est.TEXT AS sqltext, epa.value AS set_options, qp.query_plan, charindex('<ParameterList>', qp.query_plan) + len('<ParameterList>') AS paramstart, charindex('</ParameterList>', qp.query_plan) AS paramend FROM sys.dm_exec_query_stats qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) est CROSS APPLY sys.dm_exec_text_query_plan(qs.plan_handle, qs.statement_start_offset, qs.statement_end_offset) qp CROSS APPLY sys.dm_exec_plan_attributes(qs.plan_handle) epa WHERE est.objectid = object_id(@procname) AND est.dbid = db_id(@dbname) AND epa.attribute = 'set_options' ), next_level AS ( SELECT stmt_start, set_options, query_plan, CASE WHEN isencrypted = 1 THEN '-- ENCRYPTED' WHEN stmt_start >= 0 THEN substring(sqltext, stmt_start + 1, CASE stmt_end WHEN 0 THEN datalength(sqltext) ELSE stmt_end - stmt_start + 1 END) END AS Statement, CASE WHEN paramend > paramstart THEN CAST(substring(query_plan, paramstart, paramend - paramstart) AS XML) END AS params FROM basedata ) SELECT set_options AS [SET], n.stmt_start AS Pos, n.Statement, CR.c.value('@Column', 'nvarchar(128)') AS Parameter, CR.c.value('@ParameterCompiledValue', 'nvarchar(128)') AS [Sniffed Value], CAST(query_plan AS XML) AS [Query plan] FROM next_level n CROSS APPLY n.params.nodes('ColumnReference') AS CR(c) ORDER BY n.set_options, n.stmt_start, Parameter --获取表和索引的定义: DECLARE @tbl NVARCHAR(265) SELECT @tbl = 'u_ware' SELECT o.NAME, i.index_id, i.NAME, i.type_desc, substring(ikey.cols, 3, len(ikey.cols)) AS key_cols, substring(inc.cols, 3, len(inc.cols)) AS included_cols, stats_date(o.object_id, i.index_id) AS stats_date, i.filter_definition FROM sys.objects o JOIN sys.indexes i ON i.object_id = o.object_id CROSS APPLY ( SELECT ', ' + c.NAME + CASE ic.is_descending_key WHEN 1 THEN ' DESC' ELSE '' END FROM sys.index_columns ic JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 0 ORDER BY ic.key_ordinal FOR XML PATH('') ) AS ikey(cols) OUTER APPLY ( SELECT ', ' + c.NAME FROM sys.index_columns ic JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 1 ORDER BY ic.index_column_id FOR XML PATH('') ) AS inc(cols) WHERE o.NAME = @tbl AND i.type IN ( 1, 2 ) ORDER BY o.NAME, i.index_id ---获取统计信息相关信息: DECLARE @tbl NVARCHAR(265) SELECT @tbl = 'u_ware' SELECT o.NAME, s.stats_id, s.NAME, s.auto_created, s.user_created, substring(scols.cols, 3, len(scols.cols)) AS stat_cols, stats_date(o.object_id, s.stats_id) AS stats_date, s.filter_definition FROM sys.objects o JOIN sys.stats s ON s.object_id = o.object_id CROSS APPLY ( SELECT ', ' + c.NAME FROM sys.stats_columns sc JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id WHERE sc.object_id = s.object_id AND sc.stats_id = s.stats_id ORDER BY sc.stats_column_id FOR XML PATH('') ) AS scols(cols) WHERE o.NAME = @tbl ORDER BY o.NAME, s.stats_id /* 其中列stats_date返回统计信息最近更新时间。如果这个时间已经过去很久,那么统计信息可能已经过时。 参数嗅探问题的根源通常不是统计信息过时,但是也应该检查一下。 需要记住的是,统计信息的列如果是单调递增——如ID、date列,那么会很快过时,因为语句通常获取最近插入的数据, 在统计信息的直方图中,记录的却通常是旧的数据*/ --如果你认为统计信息过时,可以执行下面语句: UPDATE STATISTICS 表名 WITH FULLSCAN, INDEX --除了更新表上的全部索引,也可以用下面语句更新某个索引: UPDATE STATISTICS tbl indexname WITH FULLSCAN --为了检查索引的统计信息情况,可以使用DBCC SHOW_STATITICS命令。 --这个命令需要两个参数,第一个是表名,第二个参数是索引或统计信息的名称,但是第二个参数也可以是列名,比如: DBCC SHOW_STATISTICS (Orders, OrderDate) DBCC SHOW_STATISTICS ('u_ware', PK__u_ware__0A1E72EE) 动态管理视图和函数笔记-sql server 2005的一些动态函数 动态管理视图和函数返回可用于监视服务器实例的运行状况、诊断故障以及优化性能的服务器状态信息。 1、与执行有关的动态管理视图和函数: (*)sys.dm_exec_sessions: 是服务器范围的视图,显示了有关所有活动用户连接和内部任务的信息。此信息包含客户端版本、客户端程序名称、客户端登录时间、登录用户、当前会话设置等。 (*)sys.dm_exec_requests :返回有关在 SQL Server 中执行的每个请求的信息。 (*)sys.dm_exec_connections:返回与 SQL Server 实例建立的连接有关的信息以及每个连接的详细信息。 (*)sys.dm_exec_cursors:返回有关在各种数据库中打开的游标的信息。 比如;select * from sys.dm_exec_cursors(0) (*)sys.dm_exec_sql_text :返回由指定的 sql_handle 标识的 SQL 批处理的文本。 比如:select sql_text.* from sys.dm_exec_requests CROSS APPLY(SELECT * FROM sys.dm_exec_sql_text(sys.dm_exec_requests.sql_handle)) sql_text sys.dm_exec_background_job_queue:对计划异步(后台)执行的每个查询处理器作业返回一行。 sys.dm_exec_background_job_queue_stats:对于每个为异步(后台)执行而提交的查询处理器作业,相应地返回一行,以提供聚合统计信息。 (*)sys.dm_exec_cached_plans :针对 SQL Server 为了加快查询执行而缓存的每个查询计划返回一行。 比如:select sql_text.* from sys.dm_exec_cached_plans CROSS APPLY( SELECT * FROM sys.dm_exec_sql_text(sys.dm_exec_cached_plans.plan_handle)) sql_text sys.dm_exec_plan_attributes:针对计划句柄所指定计划的每个计划属性返回一行。 比如:select * from sys.dm_exec_plan_attributes(0x05000500AEB9A870B881125A000000000000000000000000) sys.dm_exec_text_query_plan:为 Transact-SQL 批查询或批查询中的特定语句返回文本格式的显示计划。 sys.dm_exec_query_plan:以 XML 格式返回计划句柄指定的批查询的显示计划。计划句柄指定的计划可以处于缓存或正在执行状态。 比如:select * from sys.dm_exec_query_plan(0x05000500AEB9A870B881125A000000000000000000000000) (*)sys.dm_exec_query_stats :返回缓存查询计划的聚合性能统计信息。 2、与索引有关的动态管理视图和函数 (*)sys.dm_db_index_usage_stats:返回不同类型索引操作的计数以及上次执行每种操作的时间。 sys.dm_db_index_operational_stats :返回数据库中表或索引的每个分区的当前低级 I/O、锁定、闩锁和访问方法活动。 (*)sys.dm_db_index_physical_stats :返回指定表或视图的数据和索引的大小和碎片信息。 sys.dm_db_missing_index_columns:返回与缺少索引(不包括空间索引)的数据库表列有关的信息。 (*)sys.dm_db_missing_index_details:返回有关缺失索引的详细信息,不包括空间索引。 sys.dm_db_missing_index_groups:返回有关特定缺失索引组中包含的缺失索引(不包括空间索引)的信息 sys.dm_db_missing_index_group_stats: 返回有关缺失索引组的摘要信息, 3、与 I/O 有关的动态管理视图和函数: sys.dm_io_virtual_file_stats:返回数据和日志文件的 I/O 统计信息。 比如:SELECT * FROM sys.dm_io_virtual_file_stats(db_id('taobao'),null) sys.dm_io_pending_io_requests:对于 SQL Server 中每个挂起的 I/O 请求,返回与其对应的一行。 sys.dm_io_cluster_shared_drives:如果当前服务器实例为群集服务器,则此视图返回每个共享驱动器的名称。如果当前服务器实例不是群集实例,则返回空行集。 sys.dm_io_backup_tapes:返回磁带设备的列表和用于备份的装入请求的状态。 4、与数据库有关的动态管理视图: sys.dm_db_file_space_usage:返回数据库中每个文件的空间使用信息。该视图只适用于 tempdb 数据库。 sys.dm_db_partition_stats:返回当前数据库中每个分区的页和行计数信息。 比如:SELECT * FROM sys.dm_db_partition_stats WHERE object_id = OBJECT_ID('taobaoitem_0003'); sys.dm_db_session_space_usage:返回每个会话为数据库分配和释放的页数。该视图只适用于 tempdb 数据库 sys.dm_db_task_space_usage:返回数据库任务所执行的页分配和释放活动。该视图只适用于 tempdb 数据库 5、与事务有关的动态管理视图和函数 (*)sys.dm_tran_locks:返回有关当前活动的锁管理器资源的信息。 sys.dm_tran_database_transactions:返回有关数据库级的事务的信息。 sys.dm_tran_session_transactions:返回关联事务和会话的相关信息。 所有对象: SELECT name, object_id, principal_id, schema_id, parent_object_id, type, type_desc, create_date, modify_date, is_ms_shipped, is_published, is_schema_published FROM sys.all_objects ORDER BY name 索引对象: SELECT object_id, name, index_id, type, type_desc, is_unique, data_space_id, ignore_dup_key, is_primary_key, is_unique_constraint, fill_factor, is_padded, is_disabled, is_hypothetical, allow_row_locks, allow_page_locks FROM sys.indexes 索引使用情况: SELECT database_id, object_id, index_id, user_seeks, user_scans, user_lookups, user_updates, last_user_seek, last_user_scan, last_user_lookup, last_user_update, system_seeks, system_scans, system_lookups, system_updates, last_system_seek, last_system_scan, last_system_lookup, last_system_update FROM sys.dm_db_index_usage_stats WHERE (database_id = DB_ID('taobao') ) 某数据库下索引使用情况: SELECT a.database_id, a.object_id, a.index_id, b.name, a.user_seeks, a.user_scans, a.user_lookups, a.user_updates, a.last_user_seek, a.last_user_scan, a.last_user_lookup, a.last_user_update, a.system_seeks, a.system_scans, a.system_lookups, a.system_updates, a.last_system_seek, a.last_system_scan, a.last_system_lookup, a.last_system_update FROM sys.dm_db_index_usage_stats AS a INNER JOIN sys.indexes AS b ON a.object_id = b.object_id WHERE (a.database_id = DB_ID('taobao')) 事务锁使用情况: SELECT resource_type, resource_subtype, resource_database_id, resource_description, resource_associated_entity_id, resource_lock_partition, request_mode, request_type, request_status, request_reference_count, request_lifetime, request_session_id, request_exec_context_id, request_request_id, request_owner_type, request_owner_id, request_owner_guid, request_owner_lockspace_id, lock_owner_address FROM sys.dm_tran_locks WHERE (resource_database_id = DB_ID('taobao')) 存储过程使用次数: SELECT usecounts, text, dbid, objectid FROM sys.dm_exec_cached_plans cp CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) WHERE objtype = 'Proc' and (objectid=object_id('p_prom') or dbid=db_id('hydee')); 数据库所有会话情况: SELECT session_id, login_time, host_name, program_name, host_process_id, client_version, client_interface_name, security_id, login_name, nt_domain, nt_user_name, status, context_info, cpu_time, memory_usage, total_scheduled_time, total_elapsed_time, endpoint_id, last_request_start_time, last_request_end_time, reads, writes, logical_reads, is_user_process, text_size, language, date_format, date_first, quoted_identifier, arithabort, ansi_null_dflt_on, ansi_defaults, ansi_warnings, ansi_padding, ansi_nulls, concat_null_yields_null, transaction_isolation_level, lock_timeout, deadlock_priority, row_count, prev_error, original_security_id, original_login_name, last_successful_logon, last_unsuccessful_logon, unsuccessful_logons FROM sys.dm_exec_sessions 所有请求情况: SELECT session_id, request_id, start_time, status, command, sql_handle, statement_start_offset, statement_end_offset, plan_handle, database_id, user_id, connection_id, blocking_session_id, wait_type, wait_time, last_wait_type, wait_resource, open_transaction_count, open_resultset_count, transaction_id, context_info, percent_complete, estimated_completion_time, cpu_time, total_elapsed_time, scheduler_id, task_address, reads, writes, logical_reads, text_size, language, date_format, date_first, quoted_identifier, arithabort, ansi_null_dflt_on, ansi_defaults, ansi_warnings, ansi_padding, ansi_nulls, concat_null_yields_null, transaction_isolation_level, lock_timeout, deadlock_priority, row_count, prev_error, nest_level, granted_query_memory, executing_managed_code FROM sys.dm_exec_requests 所有连接情况: SELECT session_id, most_recent_session_id, connect_time, net_transport, protocol_type, protocol_version, endpoint_id, encrypt_option, auth_scheme, node_affinity, num_reads, num_writes, last_read, last_write, net_packet_size, client_net_address, client_tcp_port, local_net_address, local_tcp_port, connection_id, parent_connection_id, most_recent_sql_handle FROM sys.dm_exec_connections 所有查询情况: SELECT sql_handle, statement_start_offset, statement_end_offset, plan_generation_num, plan_handle, creation_time, last_execution_time, execution_count, total_worker_time, last_worker_time, min_worker_time, max_worker_time, total_physical_reads, last_physical_reads, min_physical_reads, max_physical_reads, total_logical_writes, last_logical_writes, min_logical_writes, max_logical_writes, total_logical_reads, last_logical_reads, min_logical_reads, max_logical_reads, total_clr_time, last_clr_time, min_clr_time, max_clr_time, total_elapsed_time, last_elapsed_time, min_elapsed_time, max_elapsed_time FROM sys.dm_exec_query_stats 性能统计: SELECT object_name, counter_name, instance_name, cntr_value, cntr_type FROM sys.dm_os_performance_counters 索引丢失情况: SELECT index_handle, database_id, object_id, equality_columns, inequality_columns, included_columns, statement FROM sys.dm_db_missing_index_details WHERE (database_id = DB_ID('taobao')) 锁详细信息: SELECT SessionID = s.Session_id,resource_type,DatabaseName = DB_NAME(resource_database_id), request_mode,request_type,a.text,login_time,host_name,program_name,client_interface_name, login_name,nt_domain,nt_user_name,s.status, last_request_start_time, last_request_end_time,s.logical_reads,s.reads,request_status,request_owner_type,objectid,dbid,a.number, a.encrypted , a.blocking_session_id FROM sys.dm_tran_locks l JOIN sys.dm_exec_sessions s ON l.request_session_id = s.session_id LEFT JOIN (SELECT * FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(sql_handle)) a ON s.session_id = a.session_id WHERE s.session_id > 50 查询阻塞情况: SELECT blocked_query.session_id AS blocked_session_id, blocking_query.session_id AS blocking_session_id, sql_text.text AS blocking_text, waits.wait_type AS blocking_resource FROM sys.dm_exec_requests blocked_query JOIN sys.dm_exec_requests blocking_query ON blocked_query.blocking_session_id = blocking_query.session_id CROSS APPLY ( SELECT * FROM sys.dm_exec_sql_text(blocking_query.sql_handle) ) sql_text JOIN sys.dm_os_waiting_tasks waits ON waits.session_id = blocking_query.session_id