USE pubs
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
GO
BEGIN TRANSACTION
SELECT au_lname FROM authors WITH (NOLOCK)
GO
生成的锁是:
EXEC sp_lock
GO
spid dbid ObjId IndId Type Resource Mode Status
1 1 0 0 DB S GRANT
6 1 0 0 DB S GRANT
7 1 0 0 DB S GRANT
8 4 0 0 DB S GRANT
8 4 0 0 DB S GRANT
8 4 117575457 0 TAB Sch-S GRANT
9 4 0 0 DB S GRANT
9 1 21575115 0 TAB IS GRANT
SELECT object_name(117575457)
GO
-----------------------------
authors
--设tb(A,B,C)
create table #tb(A varchar(2),B varchar(2),C varchar(2))
insert into #tb
select 'a1','b1','c1'
union all select 'a2','b2','c2'
union all select 'a3','b3','c3'
--1)排它锁
--在第一个连接中执行以下语句
begin tran
update #tb
set A='aa'
where B='b2'
waitfor delay '00:00:3' --等待3秒
commit tran
--在第二个连接中执行以下语句
begin tran
select * from #tb
where B='b2'
commit tran
--若同时执行上述两个语句,则select查询必须等待update执行完毕才能执行即要等待30秒
--2)共享锁
--在第一个连接中执行以下语句
begin tran
select * from #tb holdlock --holdlock人为加锁
where B='b2'
waitfor delay '00:00:3' --等待3秒
commit tran
--在第二个连接中执行以下语句
begin tran
select A,C from #tb
where B='b2'
update #tb
set A='aa'
where B='b2'
commit tran
--若同时执行上述两个语句,则第二个连接中的select查询可以执行
--而update必须等待第一个连接中的共享锁结束后才能执行 即要等待30秒
--3)死锁
--增设tb2(D,E)
create table #tb2(D varchar(2),E varchar(2))
insert into #tb2
select 'd1','e1'
union all select 'd2','e2'
--在第一个连接中执行以下语句
begin tran
update #tb
set A='aa'
where B='b2'
waitfor delay '00:00:5'
update #tb2
set D='d5'
where E='e1'
commit tran
--在第二个连接中执行以下语句
begin tran
update #tb2
set D='d5'
where E='e1'
waitfor delay '00:00:3'
update #tb
set A='aa'
where B='b2'
commit tran