例如我怎么控制
begin tran
select @id=id from web_user where username='ll'
update web_t set holdcount=holdcount+100 where userid=@id
commit tran怎样能让用户同时触发时不会出现错误.例如两次同时请求,结果只加了100

解决方案 »

  1.   

    尝试过用锁,可能用的不对,没什么效果.
    如何做到更新结束之前,锁定username='ll'的数剧,我用行锁好象没什么效果..
      

  2.   

    同时请求肯定处理还是有先后的啊,不可能同时加200,除非你写两个UPDATE在一个事务里,那一个事务只要提交,可以加200
      

  3.   

    哦,多谢.可能上面例子说的有点不准确.
    begin tran 
    select @holdcount=holdcount from web_user where username='ll' 
    if(@holdcount>100)
       update web_user set holdcount =holdcount -100 where username='ll' 
    commit tran 
      

  4.   

    二个用户取数据时可能都取到holdcount是101,那第二个用户取到的就有问题拉..
      

  5.   

    如何让第二个用户取到的数据是第一个用户更新完后的数据呢?也就是说假如holdcount为101时,第二个用户取到的值为1而不是101呢?
      

  6.   


    --使用排它锁
    begin tran  
    select @holdcount=holdcount from web_user with (paglock,xlock) where username='ll'  
    if(@holdcount>100) 
       update web_user set holdcount =holdcount -100 where username='ll'  
    commit tran  --2使用REPEATABLEREAD锁,也可保证不会重复,但可能会死锁
    begin tran  
    select @holdcount=holdcount from web_user with (repeatableread) where username='ll'  
    if(@holdcount>100) 
       update web_user set holdcount =holdcount -100 where username='ll'  
    commit tran  --3使用SET TRANSACTION ISOLATION LEVEL  REPEATABLE READ 情况与2相同
    SET TRANSACTION ISOLATION LEVEL  REPEATABLE READ
    begin tran  
    select @holdcount=holdcount from web_user where username='ll'  
    if(@holdcount>100) 
       update web_user set holdcount =holdcount -100 where username='ll'  
    commit tran  
      

  7.   

    可以在tran中先设置独占锁,这样其他的进程就不会同时读到这个数据了。如:begin tran 
    update web_user set holdcount=holdcount where 1=2 and username='ll' 
    select @holdcount=holdcount from web_user where username='ll'  
    if(@holdcount>100) 
       update web_user set holdcount =holdcount -100 where username='ll'  
    commit tran  
      

  8.   

    上面的改一下,如下:
    begin tran  
    update web_user set holdcount=holdcount where username='ll'  
    select @holdcount=holdcount from web_user where username='ll'   
    if(@holdcount>100)  
       update web_user set holdcount =holdcount -100 where username='ll'   
    commit tran 
      

  9.   

    begin tran 
    select @id=id ,@holdcount = holdcount from web_user with (rowlock) where username='ll' 
    update web_t set holdcount=holdcount+100 where userid=@id  and  and holdcount = ,@holdcount 
    commit tran 
      

  10.   

    begin tran  
    select @id=id ,@holdcount = holdcount from web_user with (rowlock) where username='ll'  
    update web_t set holdcount=holdcount+100 where userid=@id  and  and holdcount = ,@holdcount  
    commit tran