Reputation: 149
I am struggling with getting only first 2 records from a table via FOR EACH
.
My goal is to read only first 2 records from a table, and save one field value to the variables.
Let's say I have the table MyTable
with fields PartNr
, CreationDate
, Company
, ID
.
My FOR EACH
statement would look like this:
FOR EACH MyTable
WHERE MyTable.Company = "TestCompany"
AND MyTable.CreationDate >= 01.01.2021
NO-LOCK:
END.
That FOR EACH statement would find 15 records for example. I however only need the first two.
I would like to store the PartNr
of the first
record in a variable, and the PartNr
of the second
record in another variable.
After that the FOR EACH
statement should end.
I have tried using FIND FIRST
as well, but I don't know how to get the second record then.
I am pretty much looking for a python
equivalent of break
keyword when using loops
.
Any help is much appreciated.
Upvotes: 3
Views: 2497
Reputation: 140
I know this is late, but there is another built-in solution of the FOR STATEMENT,
[variable = expression1 TO expression2[ BY k ]]
DEF VAR v-idx AS INT NO-UNDO.
FOR EACH MyTable
WHERE MyTable.Company = "TestCompany" AND
MyTable.CreationDate >= 01.01.2021
v-idx = 1 to 2 // << Loop limit
NO-LOCK:
if v-idx = 1 then do:
// store the PartNr
end.
else do: // 2
// store the PartNr in another variable
end.
end. // ends after the 2nd record
Be aware, this is a basic way to limit records, but is not a paging solution as it doesn't do an offset + a limit. You could hypothetically do that, yourself, within the loop, using this variable as a counter.
Upvotes: 0
Reputation: 772
If it really is a finite number of iterations that you know in advance, and if you are doing different logic based on the record you're up to, then you could also use a static query. It might make for cleaner code.
Something like this:
OPEN QUERY qMyQuery
FOR EACH MyTable
WHERE MyTable.Company = "TestCompany"
AND MyTable.CreationDate >= 01.01.2021
NO-LOCK.
QUERY qMyQuery:GET-FIRST.
QUERY qMyQuery:GET-NEXT.
CLOSE QUERY qMyQuery.
Upvotes: 1
Reputation: 7192
DEFINE VARIABLE iCounter AS INTEGER NO-UNDO .
myLoop:
FOR EACH MyTable
WHERE MyTable.Company = "TestCompany"
AND MyTable.CreationDate >= 01.01.2021
NO-LOCK:
iCounter = iCounter + 1 .
IF iCounter = 2 THEN
LEAVE myLoop .
END.
Upvotes: 7