如果没有事务控制,则可能会导致 select max(aid) as c1 from st_gvar; 是B已经插入后的数据。

解决方案 »

  1.   

    insert into st_gvar (fvalue) values ('');
    -- select max(aid) as c1 from st_gvar;  不用这个
    select @@IDENTITY -- 用这个,两个会话互不影响,A先执行A 行到 1,B后执行, B得到的是 2 。
      

  2.   

    不加事务会时A,B都会取到最大的,加了事务就不会,你自己可以测试一下。
    开两个会话,下面waitfor time 时间自己可以调整。
    --if object_id('test') is not null
    --drop table test
    --create table  test(id int identity(1,1) not null primary key,
    --val varchar(30))--begin tran
    waitfor time '10:18:00'
    insert into test
    values('')
    select max(id) from  test
       --commit
      

  3.   

    我用begin tran,但不加commit tran
    应该是死锁,因为会话A中max函数需要处理所有行,但会话B中insert至少会锁定某一行