在一个 StoredProcedure 中,我使用链接服务器在另一个数据库中进行一些插入/更新。已将代码包装在事务中。
CREATE PROCEDURE [mySchema].[mySP] (paramList)
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT OFF;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
DECLARE @TranStarted AS BIT = 0;
BEGIN TRY
IF @@TRANCOUNT = 0
BEGIN
BEGIN TRANSACTION;
SET @TranStarted = 1;
END
-- Do some stuff with linked server (inserts and updates on another server)
IF @TranStarted = 1
BEGIN
COMMIT TRANSACTION;
END
END TRY
BEGIN CATCH
IF @TranStarted = 1
BEGIN
ROLLBACK TRANSACTION;
END
PRINT 'ERROR_NUMBER: ' + CAST(ERROR_NUMBER() AS NVARCHAR(10));
PRINT 'ERROR_MESSAGE: ' + ERROR_MESSAGE();
PRINT 'ERROR_SEVERITY: ' + CAST(ERROR_SEVERITY() AS NVARCHAR(2));
PRINT 'ERROR_STATE: ' + CAST(ERROR_STATE() AS NVARCHAR(3));
PRINT 'ERROR_PROCEDURE: ' + ERROR_PROCEDURE();
PRINT 'ERROR_LINE: ' + CAST(ERROR_LINE() AS NVARCHAR(5));
END CATCH
END
结果如下:
ERROR_NUMBER: 3910
ERROR_MESSAGE: Transaction context in use by another session.
ERROR_SEVERITY: 16
ERROR_STATE: 2
ERROR_LINE: 1
我看过这个: 相关曲目,但我认为我没有任何环回链接服务器
没有事务块的 StoredProcedure 工作正常。
任何帮助将不胜感激。