Monday, October 10, 2011

What not to forget when using the changecompany keyword

When debugging some Ax code the other day, I stumbled upon some good looking but not working code.  What at first sight looked OK, missed a small but vital detail.

The code involved the use of the changecompany keyword.  It's an easy approach for reading records from different company accounts within one Ax database.
The syntax is pretty straightforward:

   changecompany('id')
   {
       // record handling
   }

Put the record handling between accolades and you are good to go.  But...


Example of some disfunctional code:

static void MyExample(Args _args)
{
   DataArea DataArea;
   CustTable CustTable;
   ;

   while select DataArea
      where !DataArea.isVirtual
   {
      changecompany(DataArea.id)
      {
         while select CustTable
            where CustTable.Name like 'A*'
         {
            info(strfmt("%1 %2 %3",CustTable.dataAreaId,CustTable.AccountNum,CustTable.Name));
         }
      }
   }
} 

The above does not work or gives unreliable results.
What to do: You have to reset your table variable, after the changecompany but before your perform the record handling..
Example of some working code:

static void MyExample(Args _args)
{
   DataArea DataArea;
   CustTable CustTable;
   ;

   while select DataArea
      where !DataArea.isVirtual
   {
      changecompany(DataArea.id)
      {
         CustTable=null;          // remember to reset the record object
         while select CustTable
            where CustTable.Name like 'A*'
         {
            info(strfmt("%1 %2 %3",CustTable.dataAreaId,CustTable.AccountNum,CustTable.Name));
         }
      }
   }
} 

2 comments:

  1. You saved me a lot of time. Thanks!

    ReplyDelete
  2. I have found that using
    "while select DataArea
    where !DataArea.isVirtual "
    selects companies where "DataArea.isVirtual == true".

    Has anyone else experienced this?

    ReplyDelete