--设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:10'  --等待10秒
commit tran--在第二个连接中执行以下语句
begin tran
   select * from tb where B='b2'   
commit tran
/**若同时执行上述两个语句,则select查询必须等待update执行完毕才能执行即要等待10秒,
**如果两个语句都是select操作,则两个select语句可以并行.
**只要第一句更新的行数大于零,则第二句必须等待。如果更新的行数等于零,不需要等待。
**如果使用select * from tb WITH ( NOLOCK) where B='b2',就不用等待,立即可以得到结果。 
**/--2)共享锁
--在第一个连接中执行以下语句
begin tran
   select * from tb holdlock --holdlock人为加共享锁
   where B='b2' 
   waitfor delay '00:00:10'  --等待10秒
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:10'
   update tb2 set D='d5' where E='e1' 
commit tran
   
--在第二个连接中执行以下语句
begin tran
   update tb2 set D='d5' where E='e1' 
   waitfor  delay '00:00:10'
   update tb set A='aa' where B='b2'  
commit tran--删除测试表
drop table tb,tb2--同时执行,系统会检测出死锁,第一个连接的事务可能正常执行,第二个进程死掉。
如果是死锁可以查一下:
1:sp_who 或 sp_who2
2: Select * from sysprocesses where blocked <> 0
3: 企业管理器->服务器->管理工具->活动->当前活动 然后把他kill掉
4:SQL事件探查器,監控一下,看主要是那些处理引起的锁死.然后做相应的处理.
用事件探查器new一个trace,监视一下造成你sqlserver停顿的情況
最好的办法还是检查一下引起锁的原因,一般是有你的代码引起的。----------------------------------------------------------------------
-----------------------------------------------------------------------
表中记录如下
aa b1 c1
aa b2 c2
aa b3 c3
1、执行下面这句时:
begin tran
   update tb set A='aa' where B='b2' 
   waitfor delay '00:00:10'  --等待10秒
commit tran
查看锁信息:58 10 453576654 0 PAG 1:41             IX GRANT
58 10 453576654 0 TAB                  IX GRANT
58 10 453576654 0 RID 1:41:1           X GRANT2、执行下列语句
begin tran
   update tb set A='aa' where B='b4' 
   waitfor delay '00:00:10'  --等待10秒
commit tran
查看锁信息:
58 10 453576654 0 TAB                  IX GRANT3、执行下列语句
begin tran
   update tb set A='aa' 
   waitfor delay '00:00:30'  --等待10秒
commit tran查看锁信息:
58 10 453576654 0 RID 1:41:2           X GRANT
58 10 453576654 0 RID 1:41:0           X GRANT
58 10 453576654 0 PAG 1:41             IX GRANT
58 10 453576654 0 TAB                  IX GRANT
58 10 453576654 0 RID 1:41:1           X GRANT
结论:在update操作时,在表上和页上使用IX锁,在被更新的行上使用X锁。4、执行下列语句
begin tran
   select * from tb holdlock
   waitfor delay '00:00:10'  --等待10秒
commit tran查看锁信息:
58 10 453576654 0 TAB                  S GRANT---------------------------------死锁的又一个例子
在一个查询分析器里执行
use northwindbegin tran
update customers set contactTitle='President'
where ContactTitle='Owner'打开第二个查询分析器,
执行上述语句打开第三个查询分析器
exec sp_who
exec sp_lock
可以看到状态为WAIT的锁信息