Search code examples
dynamics-business-centraldynamics-al

How can I create a nested IF without ELSE in Business Central AL


I would like to have a nested if without an inner else but I do want to have an outer else branch.

See the following procedure as an example:

procedure GetRelatedInvoiceHeader(SalesCrMemoHeader: Record "Sales Cr.Memo Header") SalesInvHeader: Record "Sales Invoice Header"
var
    CancelledDocument: Record "Cancelled Document";
    Temp: Decimal;
begin
    SalesCrMemoHeader.CalcFields(SalesCrMemoHeader.Corrective, SalesCrMemoHeader.Cancelled);
    if SalesCrMemoHeader.Corrective then
        if CancelledDocument.FindSalesCorrectiveCrMemo(SalesCrMemoHeader."No.") then
            SalesInvHeader.Get(CancelledDocument."Cancelled Doc. No.")
        else
            Temp := 0
    else
        if CancelledDocument.FindSalesCancelledCrMemo(SalesCrMemoHeader."No.") then
            SalesInvHeader.Get(CancelledDocument."Cancelled Doc. No.");
end;

The else Temp := 0 was only inserted to make the compiler happy. If the inner else is omitted, the AL compiler interprets the outer else as the inner else.

I tried semicolons and wrapped around begin .. end everywhere but it appears to me that what I want is not possible.

Is there a way to have only an outer else branch in a nested conditional statement?


Solution

  • Wrapping the outer (first) if statement in a begin end block seems to be working for me:

    procedure GetRelatedInvoiceHeader(SalesCrMemoHeader: Record "Sales Cr.Memo Header") SalesInvHeader: Record "Sales Invoice Header"
        var
            CancelledDocument: Record "Cancelled Document";
        begin
            SalesCrMemoHeader.CalcFields(SalesCrMemoHeader.Corrective, SalesCrMemoHeader.Cancelled);
            if SalesCrMemoHeader.Corrective then begin
                if CancelledDocument.FindSalesCorrectiveCrMemo(SalesCrMemoHeader."No.") then
                    SalesInvHeader.Get(CancelledDocument."Cancelled Doc. No.")
            end else
                if CancelledDocument.FindSalesCancelledCrMemo(SalesCrMemoHeader."No.") then
                    SalesInvHeader.Get(CancelledDocument."Cancelled Doc. No.");
        end;
    

    The code written like this doesn't even show the usual CodeCop AL(AA0005) warning (Only use BEGIN..END to enclose compound statements).
    It seems like there was no major oversight by the AL development team here after all.