当前位置: 代码迷 >> Sql Server >> 并发与锁解决方案
  详细解决方案

并发与锁解决方案

热度:43   发布时间:2016-04-24 09:56:59.0
并发与锁
create table st_gvar (aid int indentity(1,1) primary key,fvalue varchar(10));
insert into st_gvar (fvalue) values ('');
select max(aid) as c1 from st_gvar;

假如有两个人(A和B)同时执行insert操作,导致A得到B的记录,而B也得到B的记录?



------解决思路----------------------
不会的,有一个先取得表级排他所,待释放后,另外一个会话才能开始
------解决思路----------------------
如果没有事务控制,则可能会导致 select max(aid) as c1 from st_gvar; 是B已经插入后的数据。
------解决思路----------------------


insert into st_gvar (fvalue) values ('');
-- select max(aid) as c1 from st_gvar;  不用这个
select @@IDENTITY -- 用这个,两个会话互不影响,A先执行A 行到 1,B后执行, B得到的是 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
  相关解决方案