Loop inside a CDS view
If you have written programs in ABAP, you know that LOOP (in an internal table) is needed in almost all the programs. Now that CDS seemed to be “anointed” as a new way of coding, how can we write code in a CDS view?
So, let’s try to answer, can we write a LOOP statement in CDS view – Then the answer is NO.
But we can write logic so that loop can be grouped with conditions and grouping. Here the concept of intermediate view become so important. Let me explain with an example.
Requirement: Show in a report, material and its total quantity of items sold in a particular month.
Traditional ABAP: Fetch Data from VBAK + VBAP (fetch material, sales order creation date and the quantity sold). Loop in this table and calculate the sum total based on material and month and year.
Using CDS: Create a Basic view and fetch the data from VBAK + VBAP just like the previous step. Here in this basic view, only use the condition to convert the date to the first day of the month and the year. Create another intermediate view selecting data from the basic view created (in the previous statement) and then group the data using SUM condition ordered by Material and Date.
Sometimes you may need more than one intermediate view to get your desired result but you will get the desired result most of the times.
Share in your comments – some challenging “LOOP” which you manage to handle with the intermediate view or share cases where you need help with the intermediate views – we (and hopefully other readers) will give it a shot to resolve your issue.
As always, if you like the content, please share the blog page and linkedIn page with your contacts.