a b c
a1 b1 c1
a2 b2 c2
a3 b3 c3
1)排它锁
新建两个连接
在第一个连接中执行以下语句
begin tran
update table1
set a=aa
where b=b2
waitfor delay 00:00:30 --等待30秒
commit tran
在第二个连接中执行以下语句
begin tran
select * from table1
where b=b2
commit tran
若同时执行上述两个语句,则select查询必须等待update执行完毕才能执行即要等待30秒
2)共享锁
在第一个连接中执行以下语句
begin tran
select * from table1 holdlock -holdlock人为加锁
where b=b2
waitfor delay 00:00:30 --等待30秒
commit tran
在第二个连接中执行以下语句
begin tran
select a,c from table1
where b=b2
update table1
set a=aa
where b=b2
commit tran
若同时执行上述两个语句,则第二个连接中的select查询可以执行
而update必须等待第一个连接中的共享锁结束后才能执行 即要等待30秒
3)死锁
增设table2(d,e)
d e
d1 e1
d2 e2
在第一个连接中执行以下语句
begin tran
update table1
set a=aa
where b=b2
waitfor delay 00:00:30
update table2
set d=d5
where e=e1
commit tran
在第二个连接中执行以下语句
begin tran
update table2
set d=d5
where e=e1
waitfor delay 00:00:10
update table1
set a=aa
where b=b2
commit tran
同时执行,系统会检测出死锁,并中止进程
--------------------------------------------------------------
set implicit_transactions on --用户每次必须显式提交或回滚。否则当用户断开连接时,
--事务及其所包含的所有数据更改将回滚
set implicit_transactions off --自动提交模式。在自动提交模式下,如果各个语句成功
--完成则提交。
1 如何锁一个表的某一行
a 连接中执行
set transaction isolation level repeatable read
begin tran
select * from tablename with (rowlock) where id=3
waitfor delay 00:00:05
commit tran
b连接中如果执行
update tablename set colname=10 where id=3 --则要等待5秒
update tablename set colname=10 where id<>3 --可立即执行
2 锁定数据库的一个表
select * from table with (holdlock)
注意: 锁定数据库的一个表的区别
select * from table with (holdlock)
其他事务可以读取表,但不能更新删除
select * from table with (tablockx)
其他事务不能读取表,更新和删除
加锁语句:
sybase:
update 表 set col1=col1 where 1=0 ;
mssql:
select col1 from 表 (tablockx) where 1=0 ;
oracle:
lock table 表 in exclusive mode ;
加锁后其它人不可操作,直到加锁用户解锁,用commit或rollback解锁