How to use CrossCompany & changeCompany in Ax 2012

CrossCompany & changeCompany

CrossCompany:

You can fetch data from tables across companies using CrossCompany keyword in X++ select queries.

You can also use containers to fetch data from subset of companies.

For example,

While Select * from InventTable CrossCompany: [DAT, TEST]

{

<<Do Something here>>

}

You can also use AllowCrossCompany Property to Yes on  Queries to fetch data from across companies

changeCompany functions:

changeCompany:

You can use changeCompany function in X++ to change companies and fetch data from wherever you want

Example:

static void main()
{
CustTable custTable;
;

//Assume that you are running in company ‘aaa’.
changeCompany(‘bbb’) //Default company is now ‘bbb’.
{
custTable = null;
while select custTable
{
//custTable is now selected in company ‘bbb’.
}
}

//Default company is again set back to ‘aaa’.

changeCompany(‘ccc’) //Default company is now ‘ccc’.
{
//Clear custTable to let the select work
//on the new default company.
custTable = null;

while select custTable
{
//custTable is now selected in company ‘ccc’.
}
}

//Default company is again ‘aaa’.
}

Make table buffer to null before using it as the DataAreaID of the buffer still points out to old company – The changeCompany does not do this automatically

changeCompany (‘B’)
{
inventItemGroup = null;
inventItemGroup.ItemGroupId = ‘IB’;
inventItemGroup.insert();
}

Insert records between companies using crosscompany keyword in Ax 2012

Direct

static void CompTest(Args _args)
{
CompTest ct;
;
changecompany(“CEE”)
{
ct.Name=”Krish”;

ct.insert();
}

}

From one company to another

static void CompTest1(Args _args)
{

CompTest ctfrom,ctto;
Container _ListOfLegalEntites =[“CEU”];
;

While select crosscompany:_ListOfLegalEntites * from ctfrom

{
changecompany(“CEE”)
{
ctto.Name=ctfrom.Name;

ctto.insert();
}

}

}

From one company to another using buf2buf

static void CompTestt(Args _args)
{
CompTest itFrom;

CompTest itTo;

select itFrom where itFrom.Name==”Great”;

changeCompany(“CEU”)

{

itTo = null;

buf2buf(itFrom, itTo);

itTo.insert();

}

}

 

Using X++ Query

static void CrossCOmpanyExample(Args _args)
{
CompTest ct;
Query q;
QueryRun qr;
QueryBuildDataSource qbds ;
;
q = new query();
qbds = q.addDataSource(tablenum(CompTest));

q.allowCrossCompany(true);
q.addCompanyRange(‘CEU’);
q.addCompanyRange(‘CEE’);

qr = new QueryRun(q);

while(qr.next())
{
ct = qr.get(tablenum(CompTest));
info(strfmt(“%1 — %2”,ct.Name,ct.dataAreaId));
}
}