行级锁测试与使用(待完善)
第一行测试:行级锁对select是否有影响

第一种 情况:select id from student where id=2 没有加上锁(rowlock,updlock) 所以没有影响
结果:行执锁执行时间为2018-03-14 09:51:38.783 +等待10S
如果受影响select执行是间应为2018-03-14 09:51:48.783之后
但select实际执行时间为2018-03-14 09:51:41.200
结论:select没有影响
第二种情况加上查询加上锁 select id from student with (rowlock,updlock) where id=2
结论:select有影响
第二行测试:行级锁对update是否有影响

结果:行执锁执行时间为2018-03-14 09:59:28.643 +等待10S
如果受影响select执行是间应为2018-03-14 09:59:38.643之后
但select实际执行时间为2018-03-14 09:59:38.653
结论:update有影响
第三行测试delete是否有影响

结果:行执锁执行时间为2018-03-14 10:02:44.933 +等待10S
如果受影响delete执行是间应为2018-03-14 10:02:54.933之后
但delete实际执行时间为2018-03-14 10:02:54.937
结论:delete有影响
使用行级锁的条件:
1.查询条件必须含有主键:
查询条件必须带有一个主键:
如上表中 id为主键 name不是主键
如查询语句为:
select * from student with (rowlock,UpdLock) where name=10 则无效
select * from student with (rowlock,UpdLock) where name=10 and id=2 有效
select * from student with (rowlock,UpdLock) where id=2 有效
2.必须是 (rowlock,UpdLock)组合使用
如查询语句为
select * from student with (rowlock) where id=2 无效
select * from student with (rowlock,UpdLock) where id=2 有效
3:什么时候行锁会被解除
1:如果行锁是在事务中的,事务执行完成后同时解除行锁:
如:
begin tran
select * from student with (rowlock) where id=2
print CONVERT(varchar(100), GETDATE(), 121)+'第一次'
waitfor delay '00:00:10' --等待10S
commit tran
update student set name='10' where id =2 --需要等待上面事务执行成功后才能更新
有以下问题:update delete 操作时发只可 使用行锁 如果不使用事务 如何使用?
浙公网安备 33010602011771号