SERIALIZABLE中的锁
在SERIALIZABLE隔离级别下,sqlserver不但会锁定选择范围内的值,还会将锁定范围以外"紧邻"的值。
脚本如下
drop table ta
create table ta(c1 int,c2 int,c3 int)
go
create index index1 on ta(c1)
go
insert ta values(-10,-10,-10)
insert ta values(1,1,1)
insert ta values(5,5,5)
declare @n int=7
while @n<1000
begin
insert ta values(@n,@n,@n)
set @n+=1
end
go
create table ta(c1 int,c2 int,c3 int)
go
create index index1 on ta(c1)
go
insert ta values(-10,-10,-10)
insert ta values(1,1,1)
insert ta values(5,5,5)
declare @n int=7
while @n<1000
begin
insert ta values(@n,@n,@n)
set @n+=1
end
go
接下来选取范围从1到5的值,实际上会返回两行值,1,5
set transaction isolation level SERIALIZABLE
begin tran
select c1 from ta where c1 between 1 and 5
select * from sys.dm_tran_locks-- where request_session_id=@@SPID
select %%lockres%%,* from ta with(index=index1) where c1 between 1 and 7
--rollback
begin tran
select c1 from ta where c1 between 1 and 5
select * from sys.dm_tran_locks-- where request_session_id=@@SPID
select %%lockres%%,* from ta with(index=index1) where c1 between 1 and 7
--rollback
结合sys.dm_tran_locks和%%lockres%%,我们可以看到,1,5,7这三个键值上都有range lock,
也就是说如果有其他session尝试在1~7的范围内插入值,会被阻塞。
虽然-10没有锁,但尝试插入-10~0这些值的时候,也会被阻塞(如果查看sys.dm_tran_locks和%%lockres%%的话,会发现在是被阻塞到了1这个资源上)
要命的还在后面,如果选择如下范围:
select c1 from ta where c1 between -10 and 1
--or
select c1 from ta where c1 between 998and 999
选择了边界.
会导致向插入<-10或者>999的值都会被阻塞