AXForum  
Вернуться   AXForum > Microsoft Dynamics AX > DAX Blogs
All
Забыли пароль?
Зарегистрироваться Правила Справка Пользователи Сообщения за день Поиск Все разделы прочитаны

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 22.06.2017, 06:13   #1  
Blog bot is offline
Blog bot
Участник
 
25,459 / 846 (79) +++++++
Регистрация: 28.10.2006
stoneridgesoftware: How to Programmatically Create Queries in Dynamics AX and the Surprises Your Data Can Bring
Источник: https://stoneridgesoftware.com/progr...ata-surprises/
==============

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:



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:



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:



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:



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!



Источник: https://stoneridgesoftware.com/progr...ata-surprises/
__________________
Расскажите о новых и интересных блогах по Microsoft Dynamics, напишите личное сообщение администратору.
 

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск
Опции просмотра

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 05:35.
Powered by vBulletin® v3.8.5. Перевод: zCarot
Контактная информация, Реклама.