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

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

FieldData ElementData TypeLength
MANDTMANDTCLNT3
DEPTIDNUM10NUMC10
POSTIDNUM5NUMC5
POSTCHAR50CHAR50

Table contains the following data

DEPTIDPOSTIDPOST
10011Lieutenant
10012Captain
10013Major
10014Lieutenant Colonel
10015Colonel
10016Brigadier
10017Major general
10018Lieutenant general
10019General
100110Field 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 IDHierarchy of Posts
1001Lieutenant -> 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