Archiving data between linked servers - transaction issue

北城以北 提交于 2019-12-11 23:49:36

问题


Trying to archive some data from one database table to another over linked server connection.

So far have gotten fairly close however getting a puzzling transaction exception currently.

Here's the T-SQL:

USE ArchiveDatabase

-- Declare date we are archiving to
DECLARE @ArchiveDate DATETIME
SET @ArchiveDate = DATEADD(MONTH, -2, GETDATE())

-- Create temp table
CREATE TABLE #DeleteIDs (ID int)

-- Continue looping while rows exist
WHILE EXISTS (SELECT TOP 1 * FROM [LINKEDSERVER].MasterDatabase.dbo.Logging WITH(NOLOCK) WHERE [Date] < @ArchiveDate)

    BEGIN

        BEGIN TRANSACTION

            -- Get batch of IDs to archive
            INSERT INTO #DeleteIDs ([ID])
            (
                SELECT TOP 1000 [ID]
                FROM [LINKEDSERVER].MasterDatabase.dbo.Logging WITH(NOLOCK)
                WHERE [Date] < @ArchiveDate
            )

            -- Archive where ID is within our current batch
            INSERT INTO ArchiveDatabase.dbo.DataConnect_Logging
            ([Date],[Description],[AccountName],[ConnectionIPAddress],[HttpStatusCode],[HttpMethod],[Url])
            (
                SELECT [Date],[Description],[AccountName],[ConnectionIPAddress],[HttpStatusCode],[HttpMethod],[Url]
                FROM [LINKEDSERVER].MasterDatabase.dbo.Logging WITH(NOLOCK)
                WHERE ID IN
                (
                    SELECT ID FROM #DeleteIDs
                )
            )

            -- Remove where ID is within our current batch
            DELETE FROM [LINKEDSERVER].MasterDatabase.dbo.Logging 
            WHERE ID IN (SELECT ID FROM #DeleteIDs)

            -- Empty IDs
            DELETE FROM #DeleteIDs

            WAITFOR DELAY '00:00:02'

        -- Any errors, roll back, otherwise commit
        IF @@Error <> 0
            ROLLBACK TRANSACTION
        ELSE
            COMMIT TRANSACTION

    END 

DROP TABLE #DeleteIDs

And here's the exception:

(1000 row(s) affected)
(1000 row(s) affected)
OLE DB provider "SQLNCLI" for linked server "LINKEDSERVER" returned message "Cannot start more transactions on this session.".
Msg 7395, Level 16, State 2, Line 38
Unable to start a nested transaction for OLE DB provider "SQLNCLI" for linked server "LINKEDSERVER". A nested transaction was required because the XACT_ABORT option was set to OFF. 

回答1:


Have you tried setting XACT_ABORT to on at the start of your script?

SET XACT_ABORT ON

Unrelated, but couldn't the loop be written as:

-- Continue looping while rows exist
WHILE EXISTS (SELECT 1 FROM [LINKEDSERVER].MasterDatabase.dbo.Logging WITH(NOLOCK) 
              WHERE [Date] < @ArchiveDate)

Or even better, rewrite so that you don't hit the linked table twice per loop iteration.



来源:https://stackoverflow.com/questions/5399361/archiving-data-between-linked-servers-transaction-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!