首页 > 解决方案 > 不返回正确计数的 x++ 脚本

问题描述

我有一个 x++ 脚本,旨在从选择查询中计算记录,然后再进行更新。

这是供参考的原始问题:convert SQL Query with Join to X++ Dynamics AX scripting

最初,我有一个与之对应的 SQL Query,它产生 50 行/记录,当我将它转换为 X++ 时,它没有计算或提取相同数量的记录,

这是 x++ 脚本

static void Job(Args _args)
{

    Table1 table1;
    Table2 table2;
    Table3 table3;
    Table4 table4;
    Table5 table5;
    int i = 0;
    while select forUpdate table1  
       join table2 where table1.field1 == table2.field1 
       join table3 where table1.field2 == table3.field2
       join table4 where table3.field3 == table4.field3
       join table5 where table3.category == table5.recid
       && table1.location  == 'asia' && table2.modtye == 2
       && table3.discount == 'sample' 
       && table4.name ==  'hello' 
       &&(table5.name == 'one' || table5.name == 'two' || table5.name == 'three')                
    {    
            if (table1)    
            {
                 i = i + 1;    
            }    
    }    
    info(strfmt("Total : %1",i));    
}

请帮忙,我哪里出错了,它认为是这部分

if (table1)

我还尝试精简代码以了解问题出在哪里,

 while select forUpdate table1  
           join table2 where table1.field1 == table2.field1 
           && table1.location  == 'asia' && table2.modtye == 2

这部分还没有返回结果......当我包含

 && table1.location  == 'asia' && table2.modtye == 2

所以我认为,问题就在那里,但代码有什么问题?


我的代码实际上来自本教程链接

https://community.dynamics.com/ax/b/dynamicsaxtipoftheday/archive/2014/09/05/quickly-update-data-through-x-scripts

标签: dynamics-crm-2011axaptax++

解决方案


我建议一个简单的解释,也许 SQL 从几个公司或分区返回行?
默认情况下,AX 仅返回当前分区和公司的行curext()

如果您使用该crosscompany选项进行选择,它将扫描跨公司:

while select crosscompany table1 ...

不需要测试是否找到了table1,如果没有找到就不会进入循环。

此外,如果您的唯一目的是计算记录的数量,手动计算是浪费的,单次选择就可以了:

select firstOnly /*crosscompany*/ count(RecId) from table1  
   exists join table2 where table1.field1 == table2.field1 
   exists join table3 where table1.field2 == table3.field2
   exists join table4 where table3.field3 == table4.field3
   exists join table5 where table3.category == table5.recid
     && table1.location  == 'asia' && table2.modtye == 2
     && table3.discount == 'sample' 
     && table4.name ==  'hello' 
     &&(table5.name == 'one' || table5.name == 'two' || table5.name == 'three');
info(strfmt("Total : %1", table1.RecId));

推荐阅读