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

By Bill Thompson | June 20, 2017

How to programmatically create queries in dynamics ax and the surprises your data can bring

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

Recommended Reading:

Manage U.S. Use Tax on Purchase Orders in Dynamics 365 Finance and Operations

  Managing sales tax requirements on your business purchase can be complicated, but Dynamics 365 Finance and Operations can help […]

Read the Article
5.19.22 Dynamics CRM

How to Write a Great Support Ticket in the Stoneridge Support Portal

Submitting a support ticket through the Stoneridge Support Portal is a quick and effective way to get assistance for any […]

Read the Article

Managing Your Business Through Uncertain Times Using Dynamics 365 Finance and Operations

  Dynamics 365 Finance and Operations (F&O) can help you make informed decisions on how to move your business forward. […]

Read the Article
5.13.22 Power Platform

Using Power BI Object Level Security

  The following article will demonstrate how to use Power BI Object Level Security to disable column data based on […]

Read the Article
5.12.22 Dynamics CRM

How to Use the Stoneridge Support Portal

Stoneridge Software’s support portal is an intuitive and useful function that makes it easy for you to access resources to […]

Read the Article
5.6.22 Dynamics GP

Dynamics GP Transaction Removal: Purchase Orders

  Are you having performance issues with Purchase Orders?  Do you find that there are old Purchase Orders on your […]

Read the Article
5.5.22 Dynamics GP

The Real Story about the Long-Term Future of Dynamics GP Support

I’ve seen a number of people put forward comment that Dynamics GP is going away and you have to get […]

Read the Article

New Features in Dynamics 365 Business Central 2022 Wave 1 Release – Financial Enhancements

The Dynamics 365 Businses Central 2022 Wave 1 Release has a lot of new and exciting features to help your […]

Read the Article
4.29.22 Dynamics GP

Dynamics GP Transaction Removals: Bank Reconciliation

  This is part 2 of a 3 part series on Dynamics GP Transaction Removals. These quick tips will hopefully […]

Read the Article

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!

X