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

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 14.09.2013, 03:26   #1  
Blog bot is offline
Blog bot
Участник
 
25,475 / 846 (79) +++++++
Регистрация: 28.10.2006
How to compare two records of the same table
Источник: http://alexvoy.blogspot.com/2013/09/...ame-table.html
==============

Amongst other mundane chores, from time to time AX consultants and programmers need to check if two table records are indentical and what the difference is if they are not.

Here is a small project for AX 2012 with tmxTableBufferOperation class that provides the following static methods:
  • getOneRecordFieldList(Common _record1)
  • getTwoRecordsFieldList(Common _record1, Common _record2)
  • areIdentical(Common _record1, Common _record2)
  • getDifference(Common _record1, Common _record2)
Their names are mnemonical so you won't misunderstand what they do.

There is also a batch demonstrating how to use them:



The main idea is to use reflection DictTable class to enumerate all the fields of the given table buffer and then populate containers with its field ids, names and values.



X++:
 static public List getTwoRecordsFieldList(Common _record1, Common _record2)
{
    Common              buffer1;
    Common              buffer2;

    List                list        = new List(Types::Container);   //list of all the fields, field names and values
    List                bufferList  = new List(Types::Container);   //final list of all the fields, field names and values of these two records
    ListEnumerator      le;

    int                 i;
    fieldId             fieldId;
    DictTable           dictTable;
    DictField           dictField;

    container           c;

    if(_record1.TableId != _record2.TableId)
    {
        error(strFmt('Both records are supposed to be of the same table type!'));
    }

    dictTable = new DictTable(_record1.TableId);

    if (dictTable)
    {
        // create the list of all the fields in the table
        for (i = dictTable.fieldCnt(); i; i--)
        {
            fieldId = dictTable.fieldCnt2Id(i);
            dictField = new DictField(dictTable.id(), fieldId);
            list.addEnd([fieldId, fieldId2name(dictTable.id(), fieldId)]);
        }

        buffer1 = dictTable.makeRecord();
        buffer2 = dictTable.makeRecord();

        select buffer1 where buffer1.RecId == _record1.recId;
        select buffer2 where buffer2.RecId == _record2.recId;

        le = list.getEnumerator();
        while (le.moveNext())
        {
            c = le.current();
            bufferList.addEnd([[conPeek(c,1), conPeek(c,2), buffer1.(conPeek(c,1))],
                               [conPeek(c,1), conPeek(c,2), buffer2.(conPeek(c,1))]]);
        }
    }
    return bufferList;
}

Источник: http://alexvoy.blogspot.com/2013/09/...ame-table.html
__________________
Расскажите о новых и интересных блогах по Microsoft Dynamics, напишите личное сообщение администратору.

Последний раз редактировалось mazzy; 05.11.2013 в 14:43.
Старый 14.09.2013, 12:47   #2  
gl00mie is offline
gl00mie
Участник
MCBMSS
Most Valuable Professional
Лучший по профессии 2017
Лучший по профессии 2015
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
Лучший по профессии 2011
Лучший по профессии 2009
 
3,684 / 5788 (200) ++++++++++
Регистрация: 28.11.2005
Адрес: Москва
Записей в блоге: 3
Цитата:
Сообщение от Blog bot Посмотреть сообщение
Here is a small project for AX 2012
X++:
if(_record1.TableId != _record2.TableId)
{
    error(strFmt('Both records are supposed to be of the same table type!'));
}
В 2012-й с учетом наследования таблиц такого сравнения уже недостаточно, потому что на вход могут подать два буфера родительской таблицы, которые содержат записи из разных производных таблиц, и тогда простое сравнение по полям будет некорректно.
Цитата:
Сообщение от Blog bot Посмотреть сообщение
X++:
// create the list of all the fields in the table
for (i = dictTable.fieldCnt(); i; i--)
{
    fieldId = dictTable.fieldCnt2Id(i);
    dictField = new DictField(dictTable.id(), fieldId);
    list.addEnd([fieldId, fieldId2name(dictTable.id(), fieldId)]);
}
А вот ни разу это не даст полный список полей в случае с таблицей в иерархии наследования. Нужно еще проверить, есть ли у нее родительская таблица, и при необходимости дополнить список ее полями, и так - до корневой таблицы в иерархии. См., например, \Classes\SysDictField\findFieldById. Еще непонятно, почему было не воспользоваться dictField.name().

Последний раз редактировалось gl00mie; 14.09.2013 в 12:53.
За это сообщение автора поблагодарили: wojzeh (1).
Старый 16.09.2013, 22:17   #3  
wojzeh is offline
wojzeh
Участник
Аватар для wojzeh
Соотечественники
 
672 / 512 (19) +++++++
Регистрация: 27.04.2006
Адрес: Montreal
Дельные замечания!

Про наследование таблиц, думаю, верно. Я взял кусок стандартного кода, уж не помню, из какого класса и убрал для простоты ту часть, которая бежит по "вложенным полям".

функцию нейм() не использовал, потому что балбес.
__________________
Felix nihil admirari
 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
atinkerersnotebook: Walkthrough & Tutorial Summary Blog bot DAX Blogs 1 09.09.2013 09:11
How to make a temporary instance of a database table to be shown on the form Blog bot DAX Blogs 0 02.03.2012 01:18
Paint it black: How to color rows in Table form control Blog bot DAX Blogs 0 12.07.2011 02:11
Pawan's Ax blog: How To Restore Data In AIFSchemaStore Table Blog bot DAX Blogs 0 01.07.2010 22:07
Leon's CRM Musings: How to Find the Total Number of Records in an Account, Contact or Lead view Blog bot Dynamics CRM: Blogs 0 01.07.2010 10:05

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

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

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