在简单连接中读取未提交的数据

时间:2014-09-01 13:59:38

标签: sql sql-server transactions commit

是否有可能(在SQL SERVER 2012中)在一个事务中更新之前读取数据。 例: 我有一个表,名称:tab,有两列col1和col2。我有一条记录:col1 = 1和col2 ='a'

begin transaction
update tab set col2 = 'A' where col1 = 1
-- here i want to read data before update (in this example 'a')
-- here i want to read data after update (in this example 'A')
Committ transaction

在使用select之前提交事务之前总是在更新后获取数据(在此示例中为'A')。我试着做

select * from tab with(nolock)

但它不起作用。 问题:在部分:更新之后和提交之前 - 我可以读取更新前的数据吗? 感谢。

2 个答案:

答案 0 :(得分:0)

锁定提示可以确定您读取另一个事务正在更新的数据的效果。但是,在事务中运行的代码始终会看到先前在同一事务中所做的更改。

如果您需要旧状态,为什么不将旧版本存储在变量中?像:

begin transaction
declare @old_col2 int
select @old_col2 = col2 from tab where id = 1
update tab set col2 = 'A' where id = 1
... now you can access both the old and the new data ...

答案 1 :(得分:0)

You can achieve the same using below sample :

USE AdventureWorks2012;
GO

DECLARE @MyTableVar table(
    EmpID int NOT NULL,
    OldVacationHours int,
    NewVacationHours int,
    ModifiedDate datetime);

UPDATE TOP (10) HumanResources.Employee
SET VacationHours = VacationHours * 1.25,
    ModifiedDate = GETDATE() 
OUTPUT inserted.BusinessEntityID,
       deleted.VacationHours,
       inserted.VacationHours,
       inserted.ModifiedDate
INTO @MyTableVar;

--Display the result set of the table variable.
SELECT EmpID, OldVacationHours, NewVacationHours, ModifiedDate
FROM @MyTableVar;
GO
--Display the result set of the table.
SELECT TOP (10) BusinessEntityID, VacationHours, ModifiedDate
FROM HumanResources.Employee;
GO

这是优雅的解决方案,而不是在代码中编写单独的SELECT。 参考http://msdn.microsoft.com/en-IN/library/ms177564.aspx