Wednesday, November 24, 2010

Using while select firstonly to avoid validations in Dynamics Ax

When you execute a select statement to retrieve a single record most of us right the query first. This is followed by a validation to ensure that the query has returned a record. we make it simpler If we right it the way mentioned below

static void WhileSelectInsteadoFSelect(Args _args)
{
    CustTable custTable;
    ;

    //-----General way---------
    // fetch the record first
    select firstonly forupdate custTable;

    //add an additional validation
    if (custTable.RecId)
    {
         custTable.Memo = 'updated value';
        custTable.update();
    }

     //------Alternate--------------
    //prevents the extra 'if' check
    while select firstonly forupdate custTable
    {
        custTable.Memo = 'updated value';
        custTable.update();
    }

    //can also be used for simple readonly
    while select firstonly custTable
    {
        info(custTable.Memo);
    }
}

No comments: