如何捕获多个事务错误并将其设置为输出参数

时间:2015-07-30 16:35:32

标签: sql sql-server tsql

我是T-SQL编程的新手。我编写了以下子程序来实现两个事务。我需要使用三个输出参数来记录错误。我需要先设置@P_Return_Status = 'S'

如果On错误,在CATCH块中,我需要ROLLBACK事务; Set @P_Return_Status = ‘E’;Set @P_Error_Code = Error_Number();Set @P_Error_Messages = Error_Message()

如何输出多个(此处为两个)事务的错误并被主程序捕获。如果我的代码完全错误,请原谅我,因为我对T-SQL很新。

IF OBJECT_ID('dbo.sub_Initialize') IS NULL -- check if SP Exist
EXE('CREATE PROCEDURE dbo.sub_Initialize AS SET NOCOUNT ON;')
GO

ALTER PROCEDURE dbo.sub_Initialize 
(
@P_CurrentPeriod VARCHAR(12)
@P_Return_Status VARCHAR(1) OUT,
@P_Error_Code INT OUT,
@P_Error_Messages VARCHAR(2000) OUT
)   
AS
BEGIN

SET @P_Return_Status VARCHAR(1) = 'S'
SET @P_Error_Code INT = NULL
SET @P_Error_Messages VARCHAR(2000) = NULL

BEGIN TRANSACTION
  BEGIN TRY
    IF EXISTS (SELECT 1 FROM Rollup_Elemental_Costs WHERE Rpt_Period    = @P_CurrentPeriod)
    DELETE FROM Rollup_Elemental_Costs
    WHERE Rpt_Period = @P_CurrentPeriod
    COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
SET @P_Return_Status = ‘E’
SET @P_Error_Code = ERROR_CODE()
SET @P_Error_Messages = ERROR_MESSAGE()
END CATCH

BEGIN TRANSACTION
BEGIN TRY 
    IF EXISTS (SELECT 1 FROM Rollup_Batch_Detail_Trx WHERE Rpt_Period = @P_CurrentPeriod)
    DELETE FROM Rollup_Batch_Detail_Trx
    WHERE Rpt_Period = @P_CurrentPeriod
    COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
SET @P_Return_Status = 'E'
SET @P_Error_Code = ERROR_NUMBER()
SET @P_Error_Messages = ERROR_MESSAGE()
END CATCH
END

1 个答案:

答案 0 :(得分:0)

我建议你创建一个用于存储错误消息的表。然后将每个事务错误消息插入表中,以便稍后查询错误表以查找事务中的错误消息。

Create table error_Message
(
Transaction_identification Varchar(20) --To identify which trans generated error message
Return_Status VARCHAR(1),
Error_Code INT,
Error_Messages VARCHAR(2000) 
)

您可能需要添加更多列来标识交易详情

注意:如果您不想在物理表中存储错误消息,请将其转换为过程中的临时表。然后在过程结束时,您可以返回临时表结果

然后在CATCH块内,您可以插入error_Message

BEGIN CATCH
ROLLBACK TRANSACTION;
Insert into error_Message(Transaction_identification,Return_Status,Error_Code,Error_Me
select 'Trans 1',‘E’,ERROR_CODE(),ERROR_MESSAGE()
END CATCH