Posts

Showing posts with the label addRange

How to add empty ranges in query

In Dynamics AX programming, a common mistake I have seen when it comes to query ranges is passing an empty string value to the range. The developer here is expecting it to show all the records where the range field is empty. Instead, what we get is all records without the range being applied. As baffling as it may seems, it is easily explainable. The query engine in Dynamics AX, will not add a range if you don’t specify a value or if you specify an empty string because an empty string is treated as no value. So the following code will result in this SQL statement, query = new Query(); qbds = query.addDataSource(tableNum(ProjTable)); qbr = qbds.addRange(fieldNum(ProjTable, Name)); qbr.value(''); Select first fast * from ProjTable; But what was expected was something like, Select first fast * from ProjTable where Name == ''; So to work around this issue, use the SysQuery::valueEmptyString() static method which parses the empty strings correctly so that it...

SysQuery::findOrCreateRange() - A better way to create dynamic query ranges

When creating dynamic query ranges in X++, it is considered a best practice to create a range only if it has not been already created. I have seen examples of code where the addRange() method is called inside an executeQuery() method. This has a performance hit and should be avoided. The best approach is to create the range in the init() of the datasource. In the executeQuery(), we can find the range first, if it does not exists or has not been created at that point, create a new one and apply the values. I found a helper method on the SysQuery class which did exactly this. The method is SysQuery::findOrCreateRange(). The method takes two parameters, a datasource to add the range to and the range itself. It returns a range object.