How to Programmatically Create Queries in Dynamics AX and the Surprises Your Data Can Bring

By Bill Thompson | June 20, 2017

NOTE: For this article, a vendor has been created with the account number of MyVendor, and an account name of MyVendor, Inc.

There are times when you need to retrieve data out of Dynamics AX that will not allow you to write ‘while select…’ statements.  This is where you can create queries in Dynamics AX, and build the where clause via range values on your query.  This sounds fairly simple, but you have to be aware of what you are retrieving from the database, as you can see some rather unexpected results.

For example, say we wanted to loop through the DirPartyTable to find possible duplicates based on a vendor name.  You want to create something that is basically select * from DirPartyTable where name like ‘your name goes here’

To demonstrate this, I have created the following job (please note that this is for demonstration purposes only and used for help explain the concept I am trying to expand upon):

static void QueryRangeThoughts(Args _args)
{
    Query query;
    QueryBuildDataSource qbds;
    QueryBuildRange qbr;
    QueryRun queryRun;
    
    Counter cntr = 0;
    Counter vendCnt = 0;
    str myRange = '';
    
    VendTable vendTable;
    
    select firstOnly vendTable where vendTable.AccountNum == 'MyVendor';
    
    if (vendTable)
    {
        // get the name for the search.  We want the portion that exists prior to the first space
        cntr = strFind(vendTable.name(),' ',1,strLen(vendTable.name()));
        myRange = subStr(vendTable.name(),1,cntr - 1 ) + '*';
    }
    
    query = new query();
    qbds = query.addDataSource(tableNum(DirPartyTable));
    qbr = qbds.addRange(fieldNum(DirPartyTable,Name));
    qbr.value(myRange);
    
    queryRun = new queryRun(query);
    while (queryRun.next())
    {
        vendCnt++;
    }
    info(strFmt("Vendor count: %1",vendCnt));
    
}

When this is run, I get the following:

How to create a query in Dynamics AX infolog

Knowing my data, I know that is not correct.  So, lets figure out what is going wrong here.  What query is being generated by my code.  I modified the code to show me:

static void QueryRangeThoughtsDebug(Args _args)
{
    Query query;
    QueryBuildDataSource qbds;
    QueryBuildRange qbr;
    QueryRun queryRun;
    
    Counter cntr = 0;
    Counter vendCnt = 0;
    str myRange = '';
    
    VendTable vendTable;
    
    select firstOnly vendTable where vendTable.AccountNum == 'MyVendor';
    
    if (vendTable)
    {
        // get the name for the search.  We want the portion that exists prior to the first space
        cntr = strFind(vendTable.name(),' ',1,strLen(vendTable.name()));
        myRange = subStr(vendTable.name(),1,cntr - 1 ) + '*';        
    }
    
    query = new query();
    qbds = query.addDataSource(tableNum(DirPartyTable));
    qbr = qbds.addRange(fieldNum(DirPartyTable,Name));
    qbr.value(myRange);
    
    info (query.toString());
    
    queryRun = new queryRun(query);
    while (queryRun.next())
    {
        vendCnt++;
    }
    info(strFmt("Vendor count: %1",vendCnt));
    
}

The highlighted line is used to show me the generated query in my Infolog box:

Building Queries in Dynamics AX

Looking at what is generated, the where clause is incorrect.  The desired where clause should be myVendor* with NO OR clause.  What is going on?

After walking the code in the debugger, the issue is apparent.  Look at the range value in the debugger:

Building Queries in the Debugger, Microsoft Dynamics AX

Notice the myRange variable value is MyVendor,* in the debugger.  When this is added to the value of the query range the value is interpreted as Name = N'MyVendor' OR Name LIKE N'*' not what we want.  The comma character is NOT being removed from the vendor name string prior to the range being created.

The following code shows one way to address this:

static void QueryRangeThoughtsCompleted(Args _args)
{
    Query query;
    QueryBuildDataSource qbds;
    QueryBuildRange qbr;
    QueryRun queryRun;
    
    Counter cntr = 0;
    Counter vendCnt = 0;
    str myRange = '';
    
    VendTable vendTable;
    
    select firstOnly vendTable where vendTable.AccountNum == 'MyVendor';
    
    if (vendTable)
    {
        // get the name for the search.  We want the portion that exists prior to the first space
        cntr = strFind(vendTable.name(),' ',1,strLen(vendTable.name()));
        myRange = subStr(vendTable.name(),1,cntr - 1 ) + '*';
        myRange = strRem(myRange,',');
    }
    
    query = new query();
    qbds = query.addDataSource(tableNum(DirPartyTable));
    qbr = qbds.addRange(fieldNum(DirPartyTable,Name));
    qbr.value(myRange);
    
    info (query.toString());
    
    queryRun = new queryRun(query);
    while (queryRun.next())
    {
        vendCnt++;
    }
    info(strFmt("Vendor count: %1",vendCnt));
    
}

The strRem function was used to simply remove the comma from the range string value PRIOR to applying the string as the range.  This creates the query as desired, and gives us the information we expect:

Query object in Dynamics AX

Based on what is in my data, the above is correct, and as we can see in the query, the where condition created is what is desired.

The moral of the story ends up being “know your data”, “plan for the unexpected”, and “ test, test, test” so things like the above don’t randomly start appearing as the data changes.  The possibilities are endless in data, so we have to try to catch what we can so the expected results are shown.

Well, that’s all for now. Happy coding!

Related Posts


Under the terms of this license, you are authorized to share and redistribute the content across various mediums, subject to adherence to the specified conditions: you must provide proper attribution to Stoneridge as the original creator in a manner that does not imply their endorsement of your use, the material is to be utilized solely for non-commercial purposes, and alterations, modifications, or derivative works based on the original material are strictly prohibited.

Responsibility rests with the licensee to ensure that their use of the material does not violate any other rights.

Start the Conversation

It’s our mission to help clients win. We’d love to talk to you about the right business solutions to help you achieve your goals.

Subscribe To Our Blog

Sign up to get periodic updates on the latest posts.

Thank you for subscribing!