sql server2000 多使用者操作資料表的問題

來源:互聯網
上載者:User
今天在sql2000中做了如下測試:
建立測試表table1,其中僅包含一個欄位 ID int
僅包括一條記錄:0

操作一、
然後同時在查詢分析器的兩個視窗中執行下如下語句:

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 ) 
 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 ) 
 end

commit tran

在兩個的視窗同時執行
結果:僅有一條記錄重複

操作三、
在事務的基礎上再添加鎖機制

begin tran
declare @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 ) 
 end

commit tran

結果:40000條資料無一重複

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.