死锁杂谈
当数据库死锁时,sqlserver会释放一个优先级较低的锁,让另一个事务运行;所以,即时去捕捉数据库死锁,是挺不容易的。
如果,数据库死锁比较长时间,那么死锁是可以被捕捉的。
可以用sqlserver活动监视器来查看,哪些进程锁了数据库。
首先打开sqlserver活动监视器,然后可以看到,界面里有进程,查看资源,数据文件i/o,最近消耗大量资源的查询四项。
四项显示内容如下:
进程:在进程里可以看到哪些进程被阻塞,查看属性【阻塞者】可以看到,【阻塞者】的会话id。
等待资源:等待资源里有一些锁,可以看看那些锁累计等待时间较多。
数据文件i/o:数据文件i/o记录一些数据库mdf,ldf的读写速度。
最近消耗大量资源的查询:记录一些消耗资源较大的sql查询。
查询进程里被死锁的会话id,然后执行下面的sql,进行解锁。
declare @spid int set @spid = 518 --锁表进程会话id declare @sql varchar(1000) set @sql='kill '+cast(@spid as varchar) exec(@sql)
也可以用下面sql语句查询死锁进程,这样查询死锁进程,定位比较快。
select request_session_id spid, object_name(resource_associated_entity_id) tablename from sys.dm_tran_locks where resource_type='object'
优化杂谈
最近消耗大量资源的查询也可以用sql查询。
下面sql是查询最耗时的前10条sql语句。
select top 10 total_worker_time / 1000 as [自编译以来执行所用的cpu时间总量(ms-毫秒)], total_elapsed_time/1000 as [完成执行此计划所用的总时间], total_elapsed_time / execution_count/1000 as [平均完成执行此计划所用时间], execution_count as [上次编译以来所执行的次数], creation_time as [编译计划的时间], deqs.total_worker_time / deqs.execution_count / 1000 as [平均使用cpu时间(ms)], last_execution_time as [上次开始执行计划的时间], total_physical_reads [编译后在执行期间所执行的物理读取总次数], total_logical_reads/execution_count [平均逻辑读次数], min_worker_time /1000 as [单次执行期间所用的最小cpu时间(ms)], max_worker_time / 1000 as [单次执行期间所用的最大 cpu 时间(ms)], substring(dest.text, deqs.statement_start_offset / 2 + 1, (case when deqs.statement_end_offset = -1 then datalength(dest.text) else deqs.statement_end_offset end - deqs.statement_start_offset) / 2 + 1) as [执行sql], dest.text as [完整sql], db_name(dest.dbid) as [数据库名称], object_name(dest.objectid, dest.dbid) as [对象名称] ,deqs.plan_handle [查询所属的已编译计划] from sys.dm_exec_query_stats deqs with(nolock) cross apply sys.dm_exec_sql_text(deqs.sql_handle) as dest --平均使用cpu时间降序 order by (deqs.total_worker_time / deqs.execution_count / 1000) desc
在sqlserver活动监视器里,查看资源等待。
通常可以看到等待类别是latch的排在最上面,如下图:
latch 【闩锁】虽然是一种轻量级的锁,但等待的锁越多,肯定越影响数据库性能。
执行下面sql,查看下哪些latch比较耗资源。
select * from sys.dm_os_latch_stats
查询结果如下图所示:
从结果中可以看到各种锁类型的请求的次数,等待时间,最大等待时间(毫秒)。
但这些锁类型都是英文简写,需要使用下面表格查询它们的真实意义。
通过对比表格,我们发现了最消耗资源的access_methods_dataset_parent锁的意义是并发操作时资源访问的锁。那么想降低并发操作,就可以减少access_methods_dataset_parent锁的资源消耗了。
latch参考网址:
latch class | description |
---|---|
alloc_create_ringbuf | used internally by sql server to initialize the synchronization of the creation of an allocation ring buffer. |
alloc_create_freespace_cache | used to initialize the synchronization of internal freespace caches for heaps. |
alloc_cache_manager | used to synchronize internal coherency tests. |
alloc_freespace_cache | used to synchronize the access to a cache of pages with available space for heaps and binary large objects (blobs). contention on latches of this class can occur when multiple connections try to insert rows into a heap or blob at the same time. you can reduce this contention by partitioning the object. each partition has its own latch. partitioning will distribute the inserts across multiple latches. |
alloc_extent_cache | used to synchronize the access to a cache of extents that contains pages that are not allocated. contention on latches of this class can occur when multiple connections try to allocate data pages in the same allocation unit at the same time. this contention can be reduced by partitioning the object of which this allocation unit is a part. |
access_methods_dataset_parent | used to synchronize child dataset access to the parent dataset during parallel operations. |
access_methods_hobt_factory | used to synchronize access to an internal hash table. |
access_methods_hobt | used to synchronize access to the in-memory representation of a hobt. |
access_methods_hobt_count | used to synchronize access to a hobt page and row counters. |
access_methods_hobt_virtual_root | used to synchronize access to the root page abstraction of an internal b-tree. |
access_methods_cache_only_hobt_alloc | used to synchronize worktable access. |
access_methods_bulk_alloc | used to synchronize access within bulk allocators. |
access_methods_scan_range_generator | used to synchronize access to a range generator during parallel scans. |
access_methods_key_range_generator | used to synchronize access to read-ahead operations during key range parallel scans. |
append_only_storage_insert_point | used to synchronize inserts in fast append-only storage units. |
append_only_storage_first_alloc | used to synchronize the first allocation for an append-only storage unit. |
append_only_storage_unit_manager | used for internal data structure access synchronization within the fast append-only storage unit manager. |
append_only_storage_manager | used to synchronize shrink operations in the fast append-only storage unit manager. |
backup_result_set | used to synchronize parallel backup result sets. |
backup_tape_pool | used to synchronize backup tape pools. |
backup_log_redo | used to synchronize backup log redo operations. |
backup_instance_id | used to synchronize the generation of instance ids for backup performance monitor counters. |
backup_manager | used to synchronize the internal backup manager. |
backup_manager_differential | used to synchronize differential backup operations with dbcc. |
backup_operation | used for internal data structure synchronization within a backup operation, such as database, log, or file backup. |
backup_file_handle | used to synchronize file open operations during a restore operation. |
buffer | used to synchronize short term access to database pages. a buffer latch is required before reading or modifying any database page. buffer latch contention can indicate several issues, including hot pages and slow i/os.
this latch class covers all possible uses of page latches. sys.dm_os_wait_stats makes a difference between page latch waits that are caused by i/o operations and read and write operations on the page. |
buffer_pool_grow | used for internal buffer manager synchronization during buffer pool grow operations. |
database_checkpoint | used to serialize checkpoints within a database. |
clr_procedure_hashtable | internal use only. |
clr_udx_store | internal use only. |
clr_datat_access | internal use only. |
clr_xvar_proxy_list | internal use only. |
dbcc_check_aggregate | internal use only. |
dbcc_check_resultset | internal use only. |
dbcc_check_table | internal use only. |
dbcc_check_table_init | internal use only. |
dbcc_check_trace_list | internal use only. |
dbcc_file_check_object | internal use only. |
dbcc_perf | used to synchronize internal performance monitor counters. |
dbcc_pfs_status | internal use only. |
dbcc_object_metadata | internal use only. |
dbcc_hash_dll | internal use only. |
eventing_cache | internal use only. |
fcb | used to synchronize access to the file control block. |
fcb_replica | internal use only. |
fgcb_alloc | use to synchronize access to round robin allocation information within a filegroup. |
fgcb_add_remove | use to synchronize access to filegroups for add, drop, grow, and shrink file operations. |
filegroup_manager | internal use only. |
file_manager | internal use only. |
filestream_fcb | internal use only. |
filestream_file_manager | internal use only. |
filestream_ghost_files | internal use only. |
filestream_dfs_root | internal use only. |
log_manager | internal use only. |
fulltext_document_id | internal use only. |
fulltext_document_id_transaction | internal use only. |
fulltext_document_id_notify | internal use only. |
fulltext_logs | internal use only. |
fulltext_crawl_log | internal use only. |
fulltext_admin | internal use only. |
fulltext_amdin_command_cache | internal use only. |
fulltext_language_table | internal use only. |
fulltext_crawl_dm_list | internal use only. |
fulltext_crawl_catalog | internal use only. |
fulltext_file_manager | internal use only. |
database_mirroring_redo | internal use only. |
database_mirroring_server | internal use only. |
database_mirroring_connection | internal use only. |
database_mirroring_stream | internal use only. |
query_optimizer_vd_manager | internal use only. |
query_optimizer_id_manager | internal use only. |
query_optimizer_view_rep | internal use only. |
recovery_bad_page_table | internal use only. |
recovery_manager | internal use only. |
security_operation_rule_table | internal use only. |
security_objperm_cache | internal use only. |
security_crypto | internal use only. |
security_key_ring | internal use only. |
security_key_list | internal use only. |
service_broker_connection_receive | internal use only. |
service_broker_transmission | internal use only. |
service_broker_transmission_update | internal use only. |
service_broker_transmission_state | internal use only. |
service_broker_transmission_errors | internal use only. |
ssbxmitwork | internal use only. |
service_broker_message_transmission | internal use only. |
service_broker_map_manager | internal use only. |
service_broker_host_name | internal use only. |
service_broker_read_cache | internal use only. |
service_broker_waitfor_manager | used to synchronize an instance level map of waiter queues. one queue exists per database id, database version, and queue id tuple. contention on latches of this class can occur when many connections are: in a waitfor(receive) wait state; calling waitfor(receive); exceeding the waitfor timeout; receiving a message; committing or rolling back the transaction that contains the waitfor(receive); you can reduce the contention by reducing the number of threads in a waitfor(receive) wait state. |
service_broker_waitfor_transaction_data | internal use only. |
service_broker_transmission_transaction_data | internal use only. |
service_broker_transport | internal use only. |
service_broker_mirror_route | internal use only. |
trace_id | internal use only. |
trace_audit_id | internal use only. |
trace | internal use only. |
trace_controller | internal use only. |
trace_event_queue | internal use only. |
transaction_distributed_mark | internal use only. |
transaction_outcome | internal use only. |
nesting_transaction_readonly | internal use only. |
nesting_transaction_full | internal use only. |
msql_transaction_manager | internal use only. |
database_autoname_manager | internal use only. |
utility_dynamic_vector | internal use only. |
utility_sparse_bitmap | internal use only. |
utility_database_drop | internal use only. |
utility_dynamic_manager_view | internal use only. |
utility_debug_filestream | internal use only. |
utility_lock_information | internal use only. |
versioning_transaction | internal use only. |
versioning_transaction_list | internal use only. |
versioning_transaction_chain | internal use only. |
versioning_state | internal use only. |
versioning_state_change | internal use only. |
ktm_virtual_clock | internal use only. |
dbcc杂谈
dbcc 语句是sql server 的数据库控制台命令,共有以下四种类型。
维护:对数据库、索引或文件组进行维护的任务。
杂项:杂项任务,如启用跟踪标志或从内存中删除 dll。
信息:收集并显示各种类型信息的任务。
验证:对数据库、表、索引、目录、文件组或数据库页的分配进行的验证操作。
dbcc shrinkdatabase
dbcc shrinkdatabase用于收缩数据库,sql语句如下:
dbcc shrinkdatabase (n'库名' , 1)
执行结果如下:
各字段含义如下:
dbid:数据库引擎试图收缩的文件的数据库标识号。
fileid:数据库引擎尝试收缩的文件的文件标识号。
currentsize:文件当前占用的 8 kb 页数。
minimumsize:文件最低可以占用的 8 kb 页数。 这与文件的最小大小或最初创建时的大小相对应。
usedpages:文件当前使用的 8 kb 页数。
estimatedpages:数据库引擎估计文件能够收缩到的 8 kb 页数。
如果收缩不成功,可以查看下数据库是否有可以收缩的空间。
sql如下:
select name ,size/128.0 - cast(fileproperty(name, 'spaceused') as int)/128.0 as availablespaceinmb from sys.database_files;
如果有空间还收缩不成功,则可能是别原因。
dbcc参考网址:
数据库日志杂谈
sqlserver数据库日志对执行的sql语句进行了加密,所以,在日志里,我们看不到真正执行的sql语句。
如果想查看sql语句,需要借助一些工具,如apexsqllog。
不过,虽然看不到sql语句,也可以通过日志看出一些数据库问题,比如,可以查看数据库执行了多少次插入,更新等操作。
查看数据库日志的sql如下:
select * from [sys].[fn_dblog](null,null)
查询结果如下:
查询结果各字段含义如下:
operation |
context |
解释 |
lop_set_bits |
lcx_diff_map |
设置位图,资料: 差异(differential)备份:只备份上次完整备份后,做修改的部分。备份单位是区(extent)。意味着某个区内即使只有一页做了变动,则在差异备份里会被体现.差异备份依靠一个bitmap进行维护,一个bit对应一个区,自上次完整备份后,被修改的区会被置为1,而bitmap中被置为1对应的区会被差异备份所备份。而到下一次完整备份后,bitmap中所有的bit都会被重置为0 而这个bitmap在数据库第7页: dcm页 差异变更(differential changed map,dcm)页面他跟踪一个文件中的哪一个区在最新一次完整数据库备份之后被修改过。sqlserver用在增量备份时只对已发生数据变更的分区进行增量备份即可 |
lop_begin_xact | 事务开始 | |
lop_modify_row | lcx_heap | 修改堆表中的某一行记录 |
lop_prep_xact | 准备启动数据库 | |
lop_commit_xact | 提交事务 | |
lop_modify_row | lcx_boot_page | 修改数据库启动页 |
lop_modify_header | lcx_pfs | 修改pfs页的页头部信息 |
lop_insert_rows | lcx_clustered | 插入数据到聚集索引的索引页 |
lop_insert_rows | lcx_index_leaf | 插入数据到索引的叶子节点即数据页 |
lop_format_page | lcx_clustered | 重新组织聚集索引 |
lop_delete_split | lcx_clustered | 删除聚集索引表的一行记录引起页拆分 |
lop_modify_header | lcx_heap | 修改堆表的某页的页头信息 |
lop_begin_ckpt | lcx_null | 检查点开始 |
lop_end_ckpt | lcx_null | 检查点结束 |
lop_set_free_space | lcx_pfs | 修改pfs页设置那个数据页是空闲的 |
lop_root_change | lcx_clustered | 聚集索引的根节点改变 |
lop_insert_rows | lcx_heap | 插入数据到堆表 |
lop_format_page | lcx_heap | 格式化堆里的数据页 |
lop_lock_xact | 在事务里获取锁 | |
lop_format_page | lcx_heap | 格式化堆里的数据页 |
—————————————————————————————————-
注:此文章为原创,欢迎转载,请在文章页面明显位置给出此文链接!
若您觉得这篇文章还不错,请点击下右下角的【推荐】,非常感谢!