27 March 2017

What is wrong: crossCompany update job in AX 2012

I want to challenge you today to find an error in the following update job. Do not pay attention to the functional part. I agree, the job can be rewritten, but let's assume it must be done this way.
static void crossCompanyUpdate(Args _args)
{
    CustTable   custTable;
    CustGroup   custGroup;
    PaymTermId  oldPaymTermId = 'Net10', newPaymTermId = 'Net11';
    
    ttsBegin;

    // find all companies with oldPaymTermId
    while select crossCompany custGroup
        group by custGroup.dataAreaId
        where custGroup.PaymTermId == oldPaymTermId
    {
        changeCompany(custGroup.dataAreaId)
        {
            // disable update method
            custTable.skipDataMethods(true);

            // set newPaymTermId
            update_recordSet crossCompany custTable
                setting PaymTermId = newPaymTermId
                where custTable.PaymTermId == oldPaymTermId;
        }
    }

    ttsCommit;
}
Post your ideas into comments. I will open comments and post my solution in one week. Have fun :-)

Solution
There is no compile or runtime error, but records are updated only in one company. Table variable must be set to null within changeCompany statement, marked in orange below:
static void crossCompanyUpdate(Args _args)
{
    CustTable   custTable;
    CustGroup   custGroup;
    PaymTermId  oldPaymTermId = 'Net10', newPaymTermId = 'Net11';
    
    ttsBegin;

    // find all companies with oldPaymTermId
    while select crossCompany custGroup
        group by custGroup.dataAreaId
        where custGroup.PaymTermId == oldPaymTermId
    {
        changeCompany(custGroup.dataAreaId)
        {
            custTable = null;

            // disable update method
            custTable.skipDataMethods(true);

            // set newPaymTermId
            update_recordSet crossCompany custTable
                setting PaymTermId = newPaymTermId
                where custTable.PaymTermId == oldPaymTermId;
        }
    }

    ttsCommit;
}