insertdynamics-business-centraldynamics-albusinesscentral

How do I get the next available Line No. when inserting a line into a table using AL


I have made a codeunit in AL that lets me insert a line into the Output Journal using the Item Journal Line record in Business Central. I have managed to insert the values I want and validate them successfully, inserting one line into the table.

However, I am struggling to insert more than one line without deleting the first one. The reason for this is that I get this error: "The record in table Item Journal Line already exists. Identification fields and values: Journal Template Name='AVGANG',Journal Batch Name='STANDARD',Line No.='0' CorrelationId: fcde2248-cbd5-41b3-9655-e10a926ebed8."

I understand that the Line No. needs to change, but I am fairly new to AL, and don't quite understand how I can get the next available Line No. AI keeps suggesting that I use the function NextLineNo(), but this function is not defined in my record "Item Journal Line".

How can I get the next available Line No every time I insert a line?


Solution

  • Line numbers should be increments of 10000 e.g. 10000, 20000, 30000 etc. The reason for this is to ensure compatability with the built-in feature of the platform called AutoSplitKey.

    To get the next available line number you need to find the last record and then increment that line number by 10000:

    local procedure GetNextLineNo(JournalTemplateName: Code[20]; JournalBatchName: Code[20]) NextLineNo: Integer
    var
        ItemJournalLine: Record "Item Journal Line";
    begin
        ItemJournalLine.SetRange("Journal Template Name", JournalTemplateName);
        ItemJournalLine.SetRange("Journal Batch Name", JournalBatchName);
        
        if ItemJournalLine.FindLast() then
            NextLineNo := ItemJournalLine."Line No.";
    
        // NextLineNo will be 0 at this point if the FindLast above returned false
        NextLineNo += 10000;
    end;
    

    Then in your code you call that procedure to get the next line number:

    NextLineNo := GetNextLineNo('AVGANG', 'STANDARD');
    

    If you intend to insert multiple records by looping over some data, you should get the next line number before starting the loop and then increment that value inside the loops. This enables the platform to do bulk insert of all your lines thus increasing performance:

    NextLineNo := GetNextLineNo('AVGANG', 'STANDARD');
    
    repeat
        ... code that inserts Item Journal Line ...
        
        NextLineNo += 10000;
    until ...;