You are currently viewing Creating string out of row values on single column in ABAP

Sometimes there is a requirement during the development of software in SAP that you have to make a string out of multiple row values of single column of Internal Table. For example you have to show hierarchy of staff in a single string, or showing cities that exists between two famous cities like between Mumbai to Pune.

As we have a table of Hierarchy in which various posts of Commissioned officers of Indian Military are defined acc. to Department and their posts respectively acc. to hierarchy.

 

The following table contains ranking or posts of Commissioned officers in Indian Military. Suppose, When a person got selected as a Commissioned Officer, then he get the post of Lieutenant, and due to good performance he will be promoted to higher posts as given in table acc. to PostId.

Database Table Format

Field Data Element Data Type Length
MANDT MANDT CLNT 3
DEPTID NUM10 NUMC 10
POSTID NUM5 NUMC 5
POST CHAR50 CHAR 50

Table contains the following data

DEPTID POSTID POST
1001 1 Lieutenant
1001 2 Captain
1001 3 Major
1001 4 Lieutenant Colonel
1001 5 Colonel
1001 6 Brigadier
1001 7 Major general
1001 8 Lieutenant general
1001 9 General
1001 10 Field marshal

 

Now we have to show the Hierarchy from Lieutenant to Field marshal in a single string.
Below is the source code for the same:

DATA: BEGIN OF T_HIERARCHY,
      DEPTID       TYPE ZHIERARCHY-POSTID,
      POST        TYPE STRING,
      END OF T_HIERARCHY.
DATA: ITAB_HIERARCHY TYPE ZHIERARCHY  OCCURS 0 WITH HEADER LINE,
      IHIERARCHYDET  LIKE T_ROUTE     OCCURS 0 WITH HEADER LINE.
SELECT * INTO CORRESPONDING FIELDS OF TABLE ITAB_HIERARCHY FROM ZHIERARCHY.

SORT ITAB_HIERARCHY BY DEPTID POSTID.

LOOP AT ITAB_HIERARCHY.
IF VDEPTID <> ITAB_HIERARCHY-DEPTID.
 LOOP AT ITAB_HIERARCHY WHERE DEPTID = ITAB_HIERARCHY-DEPTID.
IF VPOST IS INITIAL.
   VPOST = ITAB_HIERARCHY-POST.
ELSE.
 CONCATENATE VPOST '->' ITAB_HIERARCHY-POST INTO VROUTE SEPARATED BY SPACE.
ENDIF.
ENDLOOP.
IHIERARCHYDET-DEPTID = ITAB_HIERARCHY-DEPTID.
IHIERARCHYDET-POST = VPOST.
APPEND IHIERARCHYDET TO IHIERARCHYDET.
CLEAR: ITAB_HIERARCHY, IHIERARCHYDET.
ENDIF.
VDEPTID = ITAB_HIERARCHY-DEPTID.
CLEAR: ITAB_HIERARCHY, IHIERARCHYDET, VPOST.
ENDLOOP.
DELETE ADJACENT DUPLICATES FROM IHIERARCHYDET COMPARING DEPTID POST.

This logic will give the following output in your table control or your report.

Dept ID Hierarchy of Posts
1001 Lieutenant -> Captain -> Major -> Lieutenant Colonel -> Colonel -> Brigadier -> Major general -> Lieutenant general -> General -> Field marshal

 

Dinesh Kumar Bansal

Dinesh Kumar Bansal is an Indian Software Developer, who is working on ASP.Net, MS-SQL, SAP-ABAP technologies from last one year. His Basic Principle of developing software is, “You have to clear about, what do you want to do, how can it be done”. He always says that development can be done with a cool & fresh mind.

Leave a Reply