Query/QueryRun with temporary tables (AX/F&O)

I noticed that some developers believe that Query* classes can’t be used to query temporary tables. It is possible; it just requires an extra step that isn’t needed with regular tables.

When working with temporary tables, each buffer (variable) of the same table can refer to a different set of temporary data. Therefore using the right buffer (reference to a particular data set) is crucial. This is true for select statements in code, form data sources, and for Query* classes as well.

If you want to query temporary tables with Query* classes, you’ll define a query (with classes like Query and QueryBuildDataSource) in exactly the same way as with regular tables. The place where you must pass references to temporary data sets is an instance of QueryRun class, namely setCursor() (or setRecord()) method.

If the query uses several temporary tables, simply call setCursor() several times – the system will find the data source for the given table. The method also has an extra parameter (_occurrence) for the case when you have multiple data sources for the same table.

Here is a complete example using standard tables, therefore anyone can simply copy and run it. It shows all steps – inserting data to temporary tables, creating a query, passing temporary tables to a QueryRun object, running the query and showing returned records. It uses F&O syntax, but the overall approach is the same in Dynamics AX too.

TmpTableName name;
 
name.RefTableId = 1;
name.TableName = 'TableA';
name.insert();
 
TmpTableIdMap map;
map.MainTableId = 1;
map.MainFieldId = 42;
map.insert();
 
Query query = new Query();
QueryBuildDataSource nameDs = query.addDataSource(tableNum(TmpTableName));
 
QueryBuildDataSource mapDs = nameDs.addDataSource(tableNum(TmpTableIdMap));
mapDs.addLink(fieldNum(TmpTableName, RefTableId), fieldNum(TmpTableIdMap, MainTableId));
 
QueryRun qr = new QueryRun(query);
qr.setCursor(name);
qr.setCursor(map);
 
while (qr.next())
{
    TmpTableName nameFetched = qr.get(tableNum(TmpTableName));
    TmpTableIdMap mapFetched = qr.get(tableNum(TmpTableIdMap));
 
    info(strFmt('%1 - %2', nameFetched.TableName, mapFetched.MainFieldId));
}

Leave a Reply

Your email address will not be published. Required fields are marked *