对一个表的第一列加上排他锁,在一个事务中假如没有完成该事务,其他用户不能对此行数据进行操作,怎么实现?
select a from aaa with (rowlock) where b = 1 还是
select a from aaa with (rowlock,xlock) where b = 1
高手点明 谢谢
...全文
14711打赏收藏
存储过程中实现行级排他锁问题
对一个表的第一列加上排他锁,在一个事务中假如没有完成该事务,其他用户不能对此行数据进行操作,怎么实现? select a from aaa with (rowlock) where b = 1 还是 select a from aaa with (rowlock,xlock) where b = 1 高手点明 谢谢
go
--因为函数中不可以用getdate,所以用个视图,得到当前时间
create view v_getdate as select dt=getdate()
go
--创建自定义函数,判断记录是否锁定
create function f_chk(@departmentid int)
returns bit
as
begin
declare @re bit,@dt datetime
select @dt=dt from v_getdate
if exists(select 1 from lock where departmentid=@departmentid
and datediff(ss,dt,@dt)<5)
set @re=1
else
set @re=0
return(@re)
end
go
--数据处理测试
if dbo.f_chk(3)=1
print '记录被锁定'
else
begin
begin tran
insert into lock values(3,getdate())
update 部门 set name='A' where departmentid=3
delete from lock where departmentid=3
commit tran
end
--删除测试环境
drop table 部门
drop view v_getdate
drop function f_chk