- READ UNCOMMITTED---未提交读(事务隔离的最低级别,仅可保证不读取物理损坏的数据)。
- READ COMMITTED---提交读(SQL Server 默认级别)锁定正在读取的行。
- REPEATABLE READ---可重复读。锁定所有读取的行
- SERIALIZABLE---可串行读(事务隔离的最高级别,事务之间完全隔离)锁定表。
- begin try
- begin tran
- insert into dbo.TransTestTable values (66,'66');
- update dbo.TransTestTable set [Name] = '77' where [Id] = 66;
- --RAISERROR ('Error raised in TRY block.',16,1);
- commit tran
- end try
- begin catch
- rollback tran
- end catch
CREATE DATABASE test
GO
--创建测试用表
USE test
GO
CREATE TABLE 帐户表
(
帐号 CHAR(4),
余额 INT
)
GO
INSERT 帐户表
SELECT 'A',100
UNION ALL
SELECT 'B',200
select * from 帐户表;
delete from 帐户表 where 帐号='B'
--脏读
BEGIN TRAN
UPDATE 帐户表 SET 余额=100 WHERE 帐号='A'
WAITFOR DELAY '00:00:10' --等待10秒
UPDATE 帐户表 SET 余额=104 WHERE 帐号='A'
COMMIT TRAN
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN TRAN
SELECT 余额 FROM 帐户表 WHERE 帐号='A'
COMMIT TRAN
-- 不可重复的读
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
--或者 SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN TRAN
SELECT 余额 FROM 帐户表 WHERE 帐号='A'
WAITFOR DELAY '00:00:10' --等待10秒
SELECT 余额 FROM 帐户表 WHERE 帐号='A'
COMMIT TRAN
BEGIN TRAN
UPDATE 帐户表 SET 余额=130 WHERE 帐号='A'
COMMIT TRAN
-- 幻读
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
--或者 SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
--或者 SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
BEGIN TRAN
SELECT * FROM 帐户表
WAITFOR DELAY '00:00:10' --等待10秒
SELECT * FROM 帐户表
COMMIT TRAN
BEGIN TRAN
INSERT INTO 帐户表 VALUES('C','300')
COMMIT TRAN