SQL Server中大事务回滚中的数据状态

时间:2012-09-14 15:35:34

标签: sql-server sql-server-2008 tsql

我有一个数据仓库程序,可以将数十个表从链接服务器下载并替换为本地数据库。每隔一段时间,代码就会卡在链接服务器上的一个表中,因为链接服务器上的表处于转换状态。我假设由于整个过程被认为是一个事务提交,当过程被卡住时,到目前为止,procrure所做的任何更改都不会被提交。但事实恰恰相反,在程序被卡住之前“下载”的表格将在本地服务器上使用今天的版本进行更新。在更改持久之前,SQL Server是否应该等待整个过程完成?

CREATE PROCEDURE MYIMPORT

AS

BEGIN


SET NOCOUNT ON

IF EXISTS (SELECT * FROM INFORMATION.SCHEMA.TABLES WHERE TABLE_NAME = 'TABLE1')
DROP TABLE TABLE1

SELECT COLUMN1, COLUMN2, COLUMN3 
INTO TABLE1
FROM OPENQUERY(MYLINK, 'SELECT COLUMN1, COLUMN2, COLUMN3 FROM TABLE1')

IF EXISTS (SELECT * FROM INFORMATION.SCHEMA.TABLES WHERE TABLE_NAME = 'TABLE2')
DROP TABLE TABLE2

SELECT COLUMN1, COLUMN2, COLUMN3 
INTO TABLE2
FROM OPENQUERY(MYLINK, 'SELECT COLUMN1, COLUMN2, COLUMN3 FROM TABLE2')
--IF THE PROCEDURE GETS STUCK HERE, THEN CHANGES TO TABLE1 WOULD HAVE BEEN MADE ON THE LOCAL SERVER WHILE NO CHANGES WOULD HAVE BEEN MADE TO TABLE3 ON THE LOCAL SERVER

IF EXISTS (SELECT * FROM INFORMATION.SCHEMA.TABLES WHERE TABLE_NAME = 'TABLE3')
DROP TABLE TABLE3

SELECT COLUMN1, COLUMN2, COLUMN3 
INTO TABLE3
FROM OPENQUERY(MYLINK, 'SELECT COLUMN1, COLUMN2, COLUMN3 FROM TABLE3')


END

2 个答案:

答案 0 :(得分:2)

SQL Server将过程中的每个语句视为单独的事务。需要添加'BEGIN TRANSACTION'和'COMMIT TRANSACTION'来将交易分组为一个。

答案 1 :(得分:0)

简而言之:存储过程!=事务。 SQL Server不为存储过程创建单独的事务。您应该自己管理交易。请参阅此链接:http://blog.sqlauthority.com/2010/06/02/sql-server-stored-procedure-and-transactions/