Remove duplicate key entry from a table

April 12, 2010 at 18:12
filed under Dynamics AX
Tagged , , ,

Sometimes, you can’t synchronize a table because is contains duplicate records. This can occur when you change field lengths on a extended data type for example.

I’ve seen people write huge SQL statements, and even jobs that create these SQL statements to remove these duplicates from a table, but there’s actually a easy way to do this in AX.

Say you have a table KLFTestDuplicates that contains duplicates, then simple run the following job to remove them.

static void KLFRemoveDuplicates(Args _args)
{
    Set fieldSet = new set(Types::Integer);

    DictIndex  dictIndex = new DictIndex(
        tablenum(KLFTestDuplicates),
        indexnum(KLFTestDuplicates, AUniqueIdx));
    int i;
    ;

    if(dictIndex.numberOfFields())
    {
        for(i=1;i<=dictIndex.numberOfFields();i++)
        {
            fieldSet.add(dictIndex.field(i));
        }

        ReleaseUpdateDB::indexAllowDup(dictIndex);

        ReleaseUpdateDB::deleteDuplicatesUsingIds(tablenum(KLFTestDuplicates), 0, fieldSet);

        ReleaseUpdateDB::indexAllowNoDup(dictIndex);
    }

    info("done");
}

Remember: this is useful when developing and testing, but it will remove data from you database, so use it with caution.

no comments

RSS / trackback

respond