sql事務對錶的鎖及With(NoLock),With(ReadPast)對錶的查詢結果對比 ...
--------------- create table tmp1 ( id int primary key, name nvarchar(20) ) ----------- insert into tmp1(id,name) values(1,'zhsan1'); insert into tmp1(id,name) values(2,'lisi1'); ------------------------------- select * from tmp1
更新(Update)語句對資料庫加鎖
----------------------------- begin tran tran1 update tmp1 set name='zhsan' where id=1 ------------------------------- select * from tmp1
查詢一直在進行,此時表已經被鎖住了
------------------------------- update tmp1 set name='lisi' where id=2 ------------------------------- select * from tmp1 where id>1
------------------------------- delete from tmp1 where id=2 ------------------------------- select * from tmp1 where id>1
查詢,更新,刪除除被鎖定的那行數據都能成功,說明被鎖住的只有id=1的那一行,對其他行的查詢,更新及刪除無影響
插入語句
------------------------------- insert into tmp1(id,name) values(3,'lisi') ------------------------------- select * from tmp1 where id>1
結果執行成功,說明插入不受影響
先將資料庫還原為
----------------------------- begin tran tran1 update tmp1 set name='zhsan' where id=1
with(readpast)與with(nolock)
------------------------------- select * from tmp1 with(readpast)
------------------------------- select * from tmp1 with(nolock)
with(readpast)會忽略被鎖住的那一行,with(nolock)不會