TRY/CATCH ErrorHandling


◎ TRY/CATCH ErrorHandling

BEGIN TRY
    BEGIN TRAN

    DECLARE @TransferAmount INT ,
            @FromBankAccountID INT ,
            @ToBankAccountID INT ,
            @FromBankAvailableBalance INT;

    SET @TransferAmount = 500000;
    SET @FromBankAccountID = 1;
    SET @ToBankAccountID = 2;

    Select  @FromBankAvailableBalance = [BankAvailableBalance]
    from    BankAccount
    where   [BankAccountID] = 1

    if ( @FromBankAvailableBalance < @TransferAmount )
        Begin
            --自定義錯誤訊息
            Raiserror('餘額大於轉出金額!!',16,1)
        END

    INSERT  INTO BankTransaction
    VALUES  ( @FromBankAccountID , @ToBankAccountID , @TransferAmount );

    UPDATE  BankAccount
    SET     [BankAvailableBalance] -= @TransferAmount
    WHERE   [BankAccountID] = @FromBankAccountID;

    UPDATE  BankAccount
    SET     [BankAvailableBalance] += @TransferAmount
    WHERE   [BankAccountID] = @ToBankAccountID;

    COMMIT TRAN;
END TRY
BEGIN CATCH
    SELECT  ERROR_NUMBER() AS [ERROR_NUMBER()] ,
            ERROR_MESSAGE() AS [ERROR_MESSAGE()] ,
            ERROR_PROCEDURE() AS [ERROR_PROCEDURE()] ,
            ERROR_STATE() AS [ERROR_STATE()] ,
            ERROR_SEVERITY() AS [ERROR_SEVERITY()] ,
            ERROR_LINE() AS [ERROR_LINE()]
END CATCH

results matching ""

    No results matching ""