• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
一个具有上进心的码农
因为一篇文章中有很多是从很多篇文章中摘取的,请恕我没有一一说明摘取出处,如果没有说明,则该文章默认是摘取,如有侵犯您的权益,请与我联系,将会马上删除。
博客园    首页    新随笔    联系   管理    订阅  订阅

SQL中的加锁

只是作为一些备用而已。 没技术含量。

请注意下面是TABLE级别的。并非行加锁。
设table1(A,B,C) 
  A        B        C 
  a1      b1      c1 
  a2      b2      c2 
  a3      b3      c3 
   
  1)排它锁 
  新建两个连接 
  在第一个连接中执行以下语句 
  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 
   
  同时执行,系统会检测出死锁,并中止进程



下面写一个行加锁的。
这里是需要等待
  SET   TRANSACTION   ISOLATION   LEVEL   REPEATABLE   READ  
 
begin   tran  
 
select   *   from   tablename   with   (rowlock)   where   id=3  
 
waitfor   delay   '00:00:05'  
 
commit   tran  
  B连接中如果执行  
 
update   tablename   set   colname='10'   where   id=3   --则要等待5秒  
  update   tablename   set   colname='10'   where   id<>3   --可立即执行  

这里不需要等待
SET   TRANSACTION   ISOLATION   LEVEL   REPEATABLE   READ  
begin tran
declare @N int
select @N=[num] from [T] with(xlock,paglock) where [id]=1  --这样的要好一点,再加一个页面锁。
if(@N<2)
   
update [T] set [num]=[num]+1 where [id]=1
commit tran

用with(rowlock xlock readpast)也可以


不过至今仍不明白这些锁的原理,  也许是我太笨吧。

posted @ 2008-07-04 11:11  不若相忘于江湖  阅读(600)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3