The while select
statement in X++ is primarily used for data handling and is one of the most commonly used forms of the select
statement. It allows you to iterate through multiple records that meet certain conditions and perform actions on each of them.
This type of loop resembles the standard select
statement in syntax, but is prefixed with while select
instead of just select
.
When using while select
for data manipulation, it’s typically enclosed in a transaction to maintain data integrity.
The query results are stored in a table buffer variable. If a field list is specified in the select
, only those fields are accessible in the buffer.
If aggregate functions like sum
, count
, or avg
are used, the computed results are stored in the respective fields. These aggregate functions work only on int
and real
data types.
The select
portion of the while select
loop is executed only once, right before the loop begins its first iteration. Any Boolean condition included in the while select
(such as iCounter < 1
) is also evaluated only a single time, which is different from the typical while
loop behavior in languages like C++ or C#.
Example 1:
int iCounter = 0;
BankAccountTable xrecBAT;
while select * from xrecBAT
where iCounter < 1
{
iCounter++;
info(strFmt("%1 , %2", iCounter, xrecBAT.AccountID));
}
In this example, the loop may execute more than once even though the condition iCounter < 1
is specified—because the condition is evaluated only once, not during each loop iteration.
Example 2:
CustTable custTable;
while select custTable
order by custTable.AccountNum
where custTable.AccountNum >= '4010' && custTable.AccountNum <= '4100'
{
info(strFmt("%1 , %2", custTable.AccountNum, custTable.SalesGroup));
}
This loop prints the AccountNum
and SalesGroup
for each customer in the CustTable
whose account number falls within the specified range.