sqlserver 获取未提交的事物

本文介绍了一个用于SQL Server的自定义存储过程,该过程能够帮助数据库管理员快速定位并解决数据库中的死锁和阻塞问题。通过创建临时表来收集有关阻塞进程的信息,并使用循环遍历这些信息来展示具体的SQL语句及其引发的问题。
create procedure sp_who_lock
as
begin
declare @spid int,@bl int,
 @intTransactionCountOnEntry  int,
        @intRowcount    int,
        @intCountProperties   int,
        @intCounter    int
 
 create table #tmp_lock_who (
 id int identity(1,1),
 spid smallint,
 bl smallint)
  
 IF @@ERROR<>0 RETURN @@ERROR
  
 insert into #tmp_lock_who(spid,bl) select  0 ,blocked
   from (select * from sysprocesses where  blocked>0 ) a 
   where not exists(select * from (select * from sysprocesses where  blocked>0 ) b 
   where a.blocked=spid)
   union select spid,blocked from sysprocesses where  blocked>0
 
 IF @@ERROR<>0 RETURN @@ERROR 
   
-- 找到临时表的记录数
 select  @intCountProperties = Count(*),@intCounter = 1
 from #tmp_lock_who
  
 IF @@ERROR<>0 RETURN @@ERROR 
  
 if @intCountProperties=0
  select '现在没有阻塞和死锁信息' as message
 
-- 循环开始
while @intCounter <= @intCountProperties
begin
-- 取第一条记录
  select  @spid = spid,@bl = bl
  from #tmp_lock_who where Id = @intCounter 
 begin
  if @spid =0 
            select '引起数据库死锁的是: '+ CAST(@bl AS VARCHAR(10)) + '进程号,其执行的SQL语法如下'
 else
            select '进程号SPID:'+ CAST(@spid AS VARCHAR(10))+ '被' + '进程号SPID:'+ CAST(@bl AS VARCHAR(10)) +'阻塞,其当前进程执行的SQL语法如下'
 DBCC INPUTBUFFER (@bl )
 end 
 
-- 循环指针下移
 set @intCounter = @intCounter + 1
end
 
drop table #tmp_lock_who
 
return 0
END




转载于:https://my.oschina.net/return/blog/646631

### 查找和删除SQL Server中的提交事务 #### 查找提交事务 为了查看当前数据库中存在的提交事务,可以利用`sys.dm_tran_active_transactions`动态管理视图以及关联其他相关视图为用户提供详细的事务信息。下面是一个用于检索长时间运行或提交事务查询: ```sql SELECT tat.name AS transaction_name, tat.transaction_id, tat.transaction_begin_time, tat.transaction_type, tat.transaction_uow, tat.transaction_state, tat.transaction_status, tat.transaction_duration = DATEDIFF(second, tat.transaction_begin_time, GETDATE()) FROM sys.dm_tran_active_transactions tat JOIN sys.dm_tran_session_transactions tst ON tat.transaction_id = tst.transaction_id WHERE tat.transaction_state IN (2, 3); -- Uncommitted or prepared states ``` 此查询返回处于活动状态但尚完成(即已准备就绪等待提交或回滚)的所有事务的信息[^1]。 #### 删除提交事务 对于那些确实需要终止的情况下的特定会话内的事务,可以通过KILL命令来强制结束对应的SPID(Session Process ID)。请注意这一步骤应当谨慎行事以免造成不必要的数据丢失或其他负面影响。以下是具体做法: 首先获取待处理事务所属进程编号: ```sql SELECT request_session_id AS spid FROM sys.dm_tran_locks WHERE resource_associated_entity_id IS NOT NULL; ``` 接着通过得到的结果集里的spid值去停止指定连接上的所有工作负荷: ```sql KILL <spid>; ``` 上述方法适用于立即中断某个具体的客户端请求及其内部可能存在的任何挂起更改操作;然而如果目标是要清理整个实例级别的残留项则建议重启服务以确保彻底清除一切潜在遗留问题[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值