Thursday 16 July 2015

X++ code to Count Records in Query

Following code illustrates how we can use SysQuery::countTotal() method to get the number of records in Query.

static void Query_cntRecords(Args _args)
{
    Query                query = new Query();
    QueryRun             queryRun;
    QueryBuildDataSource qbd;
    ;
   
    qbd = query.addDataSource(tablenum(CustTable));
    queryRun = new QueryRun(query);
   
    info(strfmt("Total Records in Query %1",SysQuery::countTotal(queryRun)));
   
}


No of ways to count the records

From data source
datasource.numberOfRowsLoaded()
From select queryselect count(RecId) from tableA;

Fetch number of records in a FormDataSource (e.g. of a Grid)

SysQuery::getTotal works fine, but the trick is how to handle temporary data sources where getTotal does not work:
if(!formDataSource.curser().isTmp())
{
    recordCount = SysQuery::getTotal(formDataSource.queryRun());
}
else
{
    while(!formDataSource.allRowsLoaded())
    {
        formDataSource.getNext();
    }
    recordCount = formDataSource.numberOfRowsLoaded();
}
Now recordCount contains the number of Records in the FormDataSource irrespective of the Tmp status of the data source. Of course the whole tmp-data source has been loaded in the process, which might be an issue in some cases.

Happy DAXing
.............

No comments:

Post a Comment