欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SQLServer 2008中通过DBCC OPENTRAN和会话查询事务

程序员文章站 2023-09-07 23:45:55
要找到最早的活动事务,可以使用dbcc opentran命令。详细用法见msdn: 给出一个示例:复制代码 代码如下: create table t_product(pk...

要找到最早的活动事务,可以使用dbcc opentran命令。详细用法见msdn:

给出一个示例:

复制代码 代码如下:

create table t_product(pkid int, pname nvarchar(50));
go

begin tran
insert into t_product values (101, '嫦娥四号');
go
dbcc opentran;
rollback tran;
go
drop table t_product;
go

执行结果:
复制代码 代码如下:

/*
(1 row(s) affected)
数据库 'testdb' 的事务信息。

最早的活动事务:
spid (服务器进程 id): 54
uid (用户 id): -1
名称 : user_transaction
lsn : (295:6687:1)
开始时间 : 12 24 2010 2:50:15:607pm
sid : 0x0105000000000005150000007fe010d31cba1ab1566ac5dff4010000
dbcc 执行完毕。如果 dbcc 输出了错误信息,请与系统管理员联系。
*/

结果显示了最早活动日志的相关信息,包括服务器进程id、用户id、和事务的开始时间。关键是spid和start time。
拥有这些信息后,可以使用动态管理视图(dmv)来检验正在执行的t-sql,以及在必要时关闭这个过程
dbcc opentran对于孤立连接(在数据库中是打开的,但与应用程序或客户端已经断开的连接)是非常有用的,并能帮助我们找出遗漏了commit或rollback的事务。该命令也返回在指定数据库内存在最早的活动事务和最早的分布式和非分布式复制事务。如果没有活动事务,则显示信息性消息,而不返回会话级数据。

我们看一个实例:
复制代码 代码如下:

set transaction isolation level serializable
begin tran

select * from t_product

insert into t_product
select 'oatest' union all
select 'oaplay'

这是一个未提交的事务,在另一个查询窗口执行如下:
复制代码 代码如下:

select session_id,transaction_id,is_user_transaction,is_local
from sys.dm_tran_session_transactions
where is_user_transaction=1

执行结果:
复制代码 代码如下:

/*返回结果
session_id transaction_id is_user_transaction is_local
54 489743 1 1
*/

返回会话id后,可以通过sys.dm_exec_connections和sys.dm_exec_sql_text来挖掘最近执行的查询的详细信息。
复制代码 代码如下:

select s.text from sys.dm_exec_connections c
cross apply sys.dm_exec_sql_text(c.most_recent_sql_handle) s
where session_id=54

这个查询返回最后执行的语句。也可以使用sys.dm_exec_requests。
因为也从sys.dm_tran_session_transactions的第一个查询中得知事务id,所以可以使用sys.dm_tran_active_transactions来了解更多事务本身的内容
复制代码 代码如下:

select transaction_begin_time,
case transaction_type
when 1 then 'read/write transaction'
when 2 then 'read-only transaction'
when 3 then 'system transaction'
when 4 then 'distributed transaction'
end tran_type,
case transaction_state
when 0 then 'not been comoletely initaialiaed yet'
when 1 then 'initaialiaed but ha notstarted'
when 2 then 'active'
when 3 then 'ended (read-only transaction)'
when 4 then 'commit initiated for distributed transaction'
when 5 then 'transaction prepared and waiting resolution'
when 6 then 'commited'
when 7 then 'being rolled back'
when 0 then 'been rolled back'
end transaction_state
from
sys.dm_tran_active_transactions
where transaction_id=455520

复制代码 代码如下:

/*结果:
transaction_begin_time tran_type transaction_state
2010-12-24 14:05:29.170 read/write transaction active
*/

小结:这里演示了使用dmv 排除故障和调查长时间的活动事务的一般技巧。基本步骤如下:
1、查询sys.dm_tran_session_transactions获取会话id和事务id之间的映射。
2、查询sys.dm_exec_connectionssys.dm_exec_sql_text查找会话最新执行的命令(most_recent_sql_handle列)
3、最后,查询sys.dm_tran_active_transactions确定事务被打开了多少时间、事务的类型和事务的状态。
使用这个技巧可以回到应用程序去查明调用的被抛弃的事务(打开但从未提交)以及那些运行时间太长或对于应用程序来说是不必要的不恰当事务。

邀月注:本文版权由邀月和博客园共同所有,转载请注明出处。