设table1(A,B,C)
A    B    C
a1   b1   c1
a2   b2   c2
a3   b3   c31)排它锁
新建两个连接
在第一个连接中执行以下语句
begin tran
   update table1
   set A='aa'
   where B='b2'
   waitfor delay '00:00:30'  --等待30秒
commit tran
在第二个连接中执行以下语句
begin tran
   select * from table1
   where B='b2'   
commit tran若同时执行上述两个语句,则select查询必须等待update执行完毕才能执行即要等待30秒2)共享锁
在第一个连接中执行以下语句
begin tran
   select * from table1 holdlock -holdlock人为加锁
   where B='b2' 
   waitfor delay '00:00:30'  --等待30秒
commit tran在第二个连接中执行以下语句
begin tran
   select A,C from table1
   where B='b2' 
   update table1
   set A='aa'
   where B='b2'   
commit tran若同时执行上述两个语句,则第二个连接中的select查询可以执行
而update必须等待第一个连接中的共享锁结束后才能执行 即要等待30秒3)死锁
增设table2(D,E)
D    E
d1   e1
d2   e2
在第一个连接中执行以下语句
begin tran
   update table1
   set A='aa'
   where B='b2' 
   waitfor  delay '00:00:30'
   update table2
   set D='d5'
   where E='e1' 
commit tran
   
在第二个连接中执行以下语句
begin tran
   update table2
   set D='d5'
   where E='e1' 
   waitfor  delay '00:00:10'
   update table1
   set A='aa'
   where B='b2'  
commit tran同时执行,系统会检测出死锁,并中止进程

解决方案 »

  1.   


    SET TRANSACTION ISOLATION LEVEL SERIALIZABLE是为了防止在事务没有完成的时候另一用户,访问事务内,未提交的数据
    create table Table1 (a int)
    go
    SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
    begin tran
      insert table1 values(1)               ----这句在事物没有commit前,被另一个用户
                                            ----访问是错误的,应为下面有可能会出错  insert table1 values('aaa')           ----这句由于类型不一样将报错
                                            ----设置了SERIALIZABLE的话就不会发生脏读
    commit transelect * from table1
      

  2.   

    客户端只使用单条的SQL语句,不要使用transaction。