declare @id intset @id = ( select max(id) from table1 )while @id < 20000 begin set @id = @id + 1 insert into table1 ( id ) select @id set @id = ( select max(id) from table1 ) end目的在于测试当两个用户同时操作同一个表时的重复性操作结果:共得到21868条数据,其中1868条重复,重复率竟高达10%分析:原因在于未对操作语句进行任何的加锁机制操作二、加上了事务处理
begin tran
declare @id int set @id = ( select max(id) from table1 )while @id < 20000 begin set @id = @id + 1 insert into table1 ( id ) select @id set @id = ( select max(id) from table1 ) endcommit tran
在两个的窗口同时执行结果:仅有一条记录重复操作三、在事务的基础上再添加锁机制begin trandeclare @id int
set @id = ( select max(id) from table1 )while @id < 40000 begin set @id = @id + 1 insert into table1 with (tablock) ( id ) select @id set @id = ( select max(id) from table1 ) endcommit tran
结果:40000条数据无一重复