多语言展示
当前在线:261今日阅读:113今日分享:31

解决SQL Server数据库表死锁【亲测有效】

解决SQL Server数据库表死锁【亲测有效】,在数据库操作或网站访问过程中偶尔会出现提示数据操作超时,以及提示被作为死锁牺牲品已终止操作等情况,都属于数据库中个别表死锁造成的,死锁的原因一般都是表的索引出现问题,如索引碎片过多,一般情况下重建索引或重新组织索引可以有效恢复正常,但是如果表数据过多,大到几十万行,前面的操作方法可能耗时太久,可先通过查找死锁的进程ID,终止Kill掉死锁的ID后再进行即可快速重建索引。
工具/原料

Microsoft SQL Server Management Studio管理工具

方法/步骤
1

打开Microsoft SQL Server Management Studio管理工具,新建查询窗口并复制运行如下命令行以创建获取数据库当前死锁进程的ID和死锁进程执行SQL语句信息的存储过程,--查看当前死锁进程SET QUOTED_IDENTIFIER ON GO SET ANSI_NULLS ON GOcreate procedure deadlockas begindeclare @spid int,@bl int, @intTransactionCountOnEntry int, @intRowcount int, @intCountProperties int, @intCounter intcreate table #tmp_lock_who ( id int identity(1,1), spid smallint, bl smallint)IF @@ERROR<>0 RETURN @@ERRORinsert 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>0IF @@ERROR<>0 RETURN @@ERROR   -- 找到临时表的记录数 select @intCountProperties = Count(*),@intCounter = 1 from #tmp_lock_whoIF @@ERROR<>0 RETURN @@ERRORif @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 enddrop table #tmp_lock_whoreturn 0 end GO SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON GO

2

打开查询分析器,执行存储过程deadlock,默认数据库为master,执行完成即可显示死锁的进程ID和操作死锁的SQL语句。

3

在查询分析器中通过运行命令行终止死锁的进程,再进行表的索引重建和重新组织即可恢复正常。--终止死锁进程IDkill 死锁进程ID

注意事项
1

死锁进程的ID直接Kill掉可能会影响正在执行的SQL语句。

2

重建索引和重新组织索引可能会影响系统的正常运行。

推荐信息