我有两个独立的存储过程,第二个在第一个存储过程的try块中调用。
第一个程序框架代码:
CREATE PROCEDURE [dbo].[Procedure1]
-- Parameters
@procedure1_parameter
AS
SET ANSI_NULLS ON
SET NOCOUNT ON
SET XACT_ABORT ON
BEGIN
BEGIN TRANSACTION;
BEGIN TRY
EXEC [dbo].[Procedure2] @procedure2_parameter;
END TRY
BEGIN CATCH
SELECT
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION;
END
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
END
第二个程序框架代码:
CREATE PROCEDURE [dbo].[Procedure2]
-- Parameters
@procedure2_parameter
AS
SET ANSI_NULLS ON
SET NOCOUNT ON
SET XACT_ABORT ON
BEGIN
BEGIN TRANSACTION;
BEGIN TRY
-- Procedure2 code
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorLine INT;
DECLARE @ErrorNumber INT;
DECLARE @ErrorProcedure NVARCHAR(200);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorNumber = ERROR_NUMBER(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE(),
@ErrorProcedure = ERROR_PROCEDURE(),
@ErrorLine = ERROR_LINE(),
@ErrorMessage = ERROR_MESSAGE();
IF @@TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION;
RAISERROR (@ErrorMessage,
@ErrorNumber,
@ErrorSeverity,
@ErrorState,
@ErrorLine,
@ErrorProcedure
);
END
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
END
正如您所看到的,它们具有几乎相同的代码,除了第二个代码在catch块中引发了错误。如果第二个程序失败,第一个程序应该从第二个程序中捕获错当我们在第一个存储过程的try块中有第二个存储过程调用时,这是处理事务回滚/提交的正确方法吗?