请问大侠: 如何判断某个表是否被锁?
------------问题描述---------------
现在我有一个事务,执行下面操作:
begin tran
step 1: delete table1(会根据条件删掉几万数据)
step 2: insert table1(先从其他表选数据,然后插入到table1)
step 3: update table1(对某些数据进行初始化)
step 4: update table2(使用table1的相应数据对table2进行某些更新)
commit tran
这个事务在差点的机器上可能需要2 到3 分钟才可以执行完毕。如果让sql自己判断,sql好似只是在commit的时候才判断表是不是被锁定。 这时候可能就是用户等了3分钟后,程序给个提示: 资源锁定,请稍候再试。 我希望在事务开始前,主动判断用到的表table1是否被锁定,锁定就不执行事务,直接给出锁定提示。
请指点如何实现呢 ? 谢谢!
------解决方案--------------------
其实你开始更新的时候加个标志位,其他进程去读取这个标志位更新前 似乎效率更高一点 不用判断锁什么的
------解决方案--------------------
- SQL code
CREATE procedure [dbo].[sp_who_lock]asbegindeclare @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 master..sysprocesses where blocked>0 ) a where not exists(select * from (select * from master..sysprocesses where blocked>0 ) b where a.blocked=spid) union select spid,blocked from master..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 <= @intCountPropertiesbegin-- 取第一条记录 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 + 1enddrop table #tmp_lock_whoreturn 0end本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/hulefei29/archive/2008/11/27/3392574.aspx
------解决方案--------------------
select resource_associated_entity_id,requestmode
from sys.dm_tran_locks
where resource_associated_entity_id = object_id('你要判断的表')