Home > Ax Technical > Using while select firstonly to avoid validations in Dynamics Ax

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)
{
    InventTable inventTable;
    ;
-----General way---------    
    //fetch the record first
    select firstonly forupdate inventtable;

    //add an additional validation
    if (inventTable.recid)
    {
        inventTable.itemName = 'newname';
        inventTable.update();
    }
    
------Alternate--------------
    //prevents the extra 'if' chek
    while select firstonly forupdate inventTable
    {
        inventTable.itemName = 'newname';
        inventTable.update();
    }
    
    //can also be used for simple readonly
    while select firstonly inventTable
    {
        Info(inventTable.ItemId);
    }
}

A few of you might already follow it but for the rest it could be a learning 🙂

[tweetmeme source=”casperkamal” http://www.url.com only_single=false]

Advertisements
  1. Patrick
    August 5, 2010 at 10:25 am

    Hi Kamal

    Klaas Deforche has analyzed this too: http://www.artofcreation.be/2009/10/22/while-select-firstonly/

    And since firstonly can return multiply records, I would only recommed, if the condition contains a unique key value, say:

    18 while select firstonly forupdate inventTable where inventTable.ItemId == “ItemA”

    19 {

    20 inventTable.itemName = ‘newname’;

    21 inventTable.update();

    22 }

  2. sams9
    August 2, 2010 at 12:50 am

    Hi Kamal,
    According to MS the use of firstonly in a while select is not recommended. http://msdn.microsoft.com/en-us/library/aa861766.aspx
    To validate I usually use just the table name even if I use a field list. e.g.
    select firstonly JournalNum, RecId from ledgerJournalTrans
    if (ledgerJournalTrans)
    {
    // Some code here
    }

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: