Blog Pages

Run dynamic sql from the linked server to the current one

SET XACT_ABORT ON; -- In order to enable the distributed transactions

BEGIN DISTRIBUTED TRANSACTION

DECLARE @SQL nvarchar(max)

BEGIN TRY
       set @SQL = 'REVERT; EXECUTE AS LOGIN = ''SA''
              EXECUTE(''
       UPDATE / INSERT / .....
       FROM [LinkedServerDataBaseName].[LinkedServerSchemaName].[LinkedServerTableName] b
       JOIN [MyServerNameAsLinkedServerName].[DataBaseName].[SchemaName].[TableName] ns  ON b.BRN_ID = ns.BRN_ID
       WHERE .......
              '') AT [LinkedServerName]';
       exec sp_executesql @SQL

       COMMIT TRANSACTION
END TRY

BEGIN CATCH

       -- ROLLBACK TRANSACTION
       -- do something....
END CATCH

SET XACT_ABORT OFF;


LinkedServerDataBaseName - database name in the linked server
MyServerNameAsLinkedServerName - my server has to be declared as linked server in the other server, this is it's linked server name there.
LinkedServerName - the linked server name in my server

No comments:

Post a Comment