Monday, November 16, 2015

Finding related data in SAP tables

Sometimes you need to find a seemingly obscure connection for some data that you have. E.g. you have a delivery number and you would like to know all the tables that that exact delivery number appears in so that you can search those records to find the second piece of information you're after.

Maybe you're trying to find all the links between a batch and a delivery so one of the tables you'll see is CHVW which might be exactly what you're after in your program's selections.

This is where my ZZFINDER program comes in handy. I use it multiple times on each project that I am on. You fill out the selection screen with the data you're after (including any leading zeroes) and hit F8.


The program will then come back with a list of table and field names to show you where this piece of data was found in the system.

So, here's the code to do this;

report zzfinder
       no standard page heading line-size 132.
* Mark Langenhoven 2015/11/14

*--- Data declarations ----------------------------------------------
"Record searching
tablesdd03ldd02l.

"Table searching
databegin of datarec,
        tabname   like dd03l-tabname,
        tabtext   like dd02t-ddtext,
        fieldname like dd03l-fieldname,
        fieldtext like dd03t-ddtext,
        data(80),
      end of datarec.
databegin of fieldrec,
        tabname   like dd03l-tabname,
        fieldname like dd03l-fieldname,
        tabclass  like dd02l-tabclass,
      end of fieldrec.

datagt_tfields like fieldrec occurs with header line.
datagt_tdata   like datarec occurs with header line.


*--- Selection screen -----------------------------------------------
selection-screen begin of block a1 with frame.
selection-screen begin of line.
selection-screen comment 1(22pdata.
parametersp_data type adrnr_txt.
selection-screen end of line.
selection-screen end of block a1.

selection-screen begin of block a2 with frame.

"Manual field definition
selection-screen begin of block a2a with frame.
selection-screen begin of line.
selection-screen comment 1(22stype.
select-options s_type for dd03l-datatype.
selection-screen end of line.

selection-screen begin of line.
selection-screen comment 1(22sleng.
select-options s_leng for dd03l-leng.
selection-screen end of line.

selection-screen begin of line.
selection-screen comment 1(22sdec.
select-options s_dec for dd03l-decimals.
selection-screen end of line.

selection-screen begin of line.
selection-screen comment 1(22sdom.
select-options s_dom for dd03l-domname.
selection-screen end of line.

selection-screen begin of line.
selection-screen comment 1(22skey.
select-options s_key for dd03l-keyflag no intervals.
selection-screen end of line.

selection-screen end of block a2a.

selection-screen comment 1(38eor.

"Field definition by example
selection-screen begin of block a2b with frame.
selection-screen begin of line.
selection-screen comment 1(22ptabnam.
parameters p_tabnam like dd03l-tabname.
selection-screen end of line.

selection-screen begin of line.
selection-screen comment 1(22pfieldn.
parameters p_fieldn like dd03l-fieldname.
selection-screen end of line.

selection-screen end of block a2b.

selection-screen end of block a2.

"Matching strategy
selection-screen begin of block a3 with frame.
selection-screen begin of line.
selection-screen comment 1(15pexact.
parameters p_exact radiobutton group smde.


selection-screen comment 25(15paddbf.
parameters p_addbf radiobutton group smde.
selection-screen end of line.

selection-screen end of block a3.

"Search limits
selection-screen begin of block a4 with frame.
selection-screen comment 1(35slimit.
selection-screen begin of line.
selection-screen comment 1(22stable.
select-options s_table for dd03l-tabname.
selection-screen end of line.

selection-screen begin of line.
selection-screen comment 1(22sfield.
select-options s_field for dd03l-fieldname.
selection-screen end of line.

"Exclude tables starting with a slash
selection-screen begin of line.
parametersp_noslsh as checkbox default 'X'.
selection-screen comment 5(22snoslash.
selection-screen end of line.

selection-screen end of block a4.



initialization.
  pdata   'Data to find'.
  stype   'Data type'.
  sleng   'Data length'.
  sdec    'Num. of decimals'.
  sdom    'Domain name'.
  skey    'Key flag'.
  eor     'Fill in block above OR block below'.
  ptabnam 'Reference table'.
  pfieldn 'Reference field'.
  pexact  'Match exactly'.
  paddbf  'Match subtext'.
  slimit  'Search limits:'.
  stable  'Search tables'.
  sfield  'Search fields'.
  snoslash 'Exclude tables with /'.


at selection-screen.
  perform validate_inputs.

*=== Main program ===================================================
start-of-selection.
  "Search through all tables to find some data
  perform search_all_tables.


at line-selection.
  perform goto_table using sy-cucol sy-lisel.


*&---------------------------------------------------------------------*
*&      Form  search_all_tables
*&---------------------------------------------------------------------*
form search_all_tables.

  "Check for wild cards
  if p_data cs '*'.
    p_addbf abap_true.
    p_exact abap_false.
    "Strip off the * because the selects don't like them
    translate p_data using ' `'.
    translate p_data using '* '.
    condense p_data no-gaps.
    translate p_data using '` '.
    message s000(38with 'Subset matching selected for wildcards'.
  endif.

  perform find_fields tables gt_tfields.

  perform find_data tables gt_tfields
                             gt_tdata.

  perform disp_data tables gt_tdata.

endform.                    "search_all_tables



*&---------------------------------------------------------------------*
*&      Form  VALIDATE_INPUTS
*&---------------------------------------------------------------------*
* Make sure we have valid stuff entered
*----------------------------------------------------------------------*
form validate_inputs .
  if p_data is initial.
    message e000(38with 'Enter some data to search for'.
  endif.

  "See if the user hasn't defined the field in some way or another
  if s_type[] is initial and
     s_dom[] is initial and
     p_tabnam is initial and
     p_fieldn is initial.
    message e000(38with 'Enter field definitions'.
  endif.

  if p_tabnam is not initial and
     p_fieldn is initial.
    message e000(38with 'Enter a table and field name in the definition'.
  endif.
  if p_tabnam is initial and
     p_fieldn is not initial.
    message e000(38with 'Enter a table and field name in the definition'.
  endif.

endform.                    " VALIDATE_INPUTS


*&---------------------------------------------------------------------*
*&      Form  find_fields
*&---------------------------------------------------------------------*
* Find the fields which match our search criteria
*----------------------------------------------------------------------*
form find_fields  tables   pt_fields structure fieldrec.

  databegin of dd02lrec,
          tabname  like dd02l-tabname,
          tabclass like dd02l-tabclass,
        end of dd02lrec.

  datalt_dd02l   like dd02lrec occurs with header line,
        lt_dd02l2  like dd02lrec occurs with header line,
        lv_lines   type i,
        lv_msg(50type c,
        lt_fields  like fieldrec occurs with header line.


  "Use the alternate field definition if the user has requested it
  perform build_fields.

  "If we are not dealing with an exact match, then allow for larger data elements
  if p_addbf abap_true.
    loop at s_leng .
      if s_leng-option 'EQ'.
        s_leng-option 'GE'.
        modify s_leng.
      endif.
    endloop.
  endif.

  "Exclude tables starting with /
  if p_noslsh abap_true.
    read table s_table with key low '/*'.
    if sy-subrc <> 0.
      s_table-low '/*'.
      s_table-option 'CP'.
      s_table-sign 'E'.
      append s_table.
    endif.

  endif.

  call function 'SAPGUI_PROGRESS_INDICATOR'
    exporting
      text 'Getting fields...'.


  select tabname fieldname from dd03l
        into corresponding fields of table lt_fields
        package size 10 "Can run for a long time
        where tabname in s_table
        and   fieldname in s_field
        and   datatype in s_type
        and   leng in s_leng
        and   decimals  in s_dec
        and   domname in s_dom
        and   keyflag in s_key.

    append lines of lt_fields to pt_fields.
    describe table pt_fields.
    lv_msg |Getting fields..{ sy-tfill }|.

    call function 'SAPGUI_PROGRESS_INDICATOR'
      exporting
        text lv_msg.


  endselect.


  check pt_fields[] is not initial.

  "Reduce the select time on the next two selects
  refresh lt_fields.
  append lines of pt_fields to lt_fields.
  sort lt_fields by tabname.
  delete adjacent duplicates from lt_fields comparing tabname.

  call function 'SAPGUI_PROGRESS_INDICATOR'
    exporting
      text 'Checking tables...'.

  "Make sure we only grab tables and not structures
  select tabname tabclass from dd02l into table lt_dd02l
         for all entries in lt_fields
         where tabname lt_fields-tabname
         and tabclass 'INTTAB' or
               tabclass 'APPEND' or
               tabclass 'VIEW' ).

  "Only activated tables allowed
  select tabname tabclass from dd02l into table lt_dd02l2
         for all entries in lt_fields
         where tabname lt_fields-tabname
         and   as4local <> 'A'.
  if sy-subrc 0.
    append lines of lt_dd02l2 to lt_dd02l.
  endif.

  sort lt_dd02l by tabname.
  delete adjacent duplicates from lt_dd02l comparing tabname.


  loop at lt_dd02l.
    delete pt_fields where tabname lt_dd02l-tabname.

    check sy-tabix mod 100 0.
    describe table pt_fields.
    lv_msg |Reducing fields..{ sy-tfill }|.

    call function 'SAPGUI_PROGRESS_INDICATOR'
      exporting
        text lv_msg.

  endloop.


  select tabname tabclass from dd02l into table lt_dd02l
           for all entries in pt_fields
           where tabname pt_fields-tabname.
  sort lt_dd02l by tabname.

  loop at pt_fields.
    read table lt_dd02l with key tabname pt_fields-tabname
                                binary search.
    pt_fields-tabclass lt_dd02l-tabclass.
    modify pt_fields.
  endloop.


  describe table pt_fields lines lv_lines.
  write:'Number of matching fields found: 'lv_lines.

*  message 'Done' type 'S'.

  call function 'SAPGUI_PROGRESS_INDICATOR'
    exporting
      text 'Fields selected'.

endform.                    " find_fields



*&---------------------------------------------------------------------*
*&      Form  find_data
*&---------------------------------------------------------------------*
* Search through our list of fields to see if we can find a match on
* our data
*----------------------------------------------------------------------*
form find_data  tables   pt_fields structure fieldrec
                         pt_data structure datarec.

  databegin of tabrec,
          data(80),
        end of tabrec.
  datalt_tab       like tabrec occurs with header line,
        lv_lines     type i,
        lv_total     type i,
        lv_tables    type i,
        lv_count     type i,
        lv_perc      type i,
        lv_cond      type string,
        lv_tabix(10),
        lv_msg(80).

  datals_old        like datarec,
        lv_counter(3type n.


  check pt_fields[] is not initial.

  describe table pt_fields lines lv_tables.

  loop at pt_fields .
    refresh lt_tab.

    "Update the job log with a status message
    lv_count sy-tabix mod 100.
    if lv_count 0.
*      WRITE sy-tabix TO lv_tabix.
      lv_msg | Searching table { sy-tabix } of { lv_tables } |.
      if lv_tables 0.
        lv_perc 0.
      else.
        lv_perc sy-tabix * 100 / lv_tables.
      endif.

      call function 'SAPGUI_PROGRESS_INDICATOR'
        exporting
          percentage lv_perc
          text       lv_msg.
    endif.

    refresh lt_tab.
    if p_exact abap_true.
      concatenate '''' p_data '''' into lv_cond.
      concatenate pt_fields-fieldname '=' lv_cond into lv_cond separated by space.
      select single (pt_fields-fieldnamefrom (pt_fields-tabname)
          into tabrec
          where (lv_cond).
      append tabrec to lt_tab.

    else.
      if pt_fields-tabclass 'POOL' or
         pt_fields-tabclass 'CLUSTER'.
        "Cannot optimize with DISTINCT on pool or cluster tables
        select (pt_fields-fieldnamefrom (pt_fields-tabname)
            into table lt_tab.

      else.

        select distinct (pt_fields-fieldnamefrom (pt_fields-tabname)
            into table lt_tab.

      endif.
    endif.

    if sy-subrc 0.

      describe table lt_tab lines lv_lines.
      lv_total lv_total + lv_lines.

      if p_exact abap_true.
        "Match the values exactly
        read table lt_tab with key data p_data.

        if sy-subrc 0.

          move-corresponding pt_fields to pt_data.
          pt_data-data lt_tab-data.
          append pt_data.

        endif.
      else.
        "Match any string which contains our string
        loop at lt_tab .
          find p_data in lt_tab-data.
          if sy-subrc 0.

            move-corresponding pt_fields to pt_data.
            pt_data-data lt_tab-data.
            append pt_data.

          endif.

        endloop.
      endif.

    endif.
  endloop.


  "Clean up the output a little bit
  sort pt_data.
  delete adjacent duplicates from pt_data.

  loop at pt_data.
    if pt_data-tabtext is initial.
      select single ddtext from dd02t into pt_data-tabtext
             where tabname pt_data-tabname
             and   ddlanguage sy-langu.
      modify pt_data transporting tabtext where tabname pt_data-tabname.
    endif.

    if pt_data-fieldtext is initial.
      select single ddtext from dd03t into pt_data-fieldtext
        where tabname pt_data-tabname
        and   fieldname pt_data-fieldname
        and   ddlanguage sy-langu.
      if sy-subrc <> 0.
        select single ddtext from dd04t into pt_data-fieldtext
          where rollname pt_data-fieldname
          and   ddlanguage sy-langu.
      endif.

      modify pt_data transporting fieldtext where fieldname pt_data-fieldname.
    endif.
  endloop.

  write'Number of data items checked   : 'lv_total.
  write/.

endform.                    " find_data


*&---------------------------------------------------------------------*
*&      Form  disp_data
*&---------------------------------------------------------------------*
* Display the data we found
*----------------------------------------------------------------------*
form disp_data  tables   pt_data structure datarec.

  datalv_lines(5type n.
  datals_old         like datarec,
        lv_count       type i,
        lv_line(90),
        lv_tabcount(5type n.

  "First write down what we searched for - useful for running multiple
  "background jobs
  write'Searched for: '.
  write/ p_data.

  skip.

  lv_count 0.
  lv_tabcount 0.
  loop at pt_data .
    "If we've searched for an exact value then there's no need to
    "display it for every table
    if p_exact is initial.

      if pt_data-tabname ls_old-tabname and
         pt_data-fieldname ls_old-fieldname.
        lv_count lv_count + 1.
        if lv_count 1.
          write'|        Multiple values found         ' color col_group,
                   at 86 '|'.
        endif.
      else.
        "If we have a single value then write it out for us to see
        if lv_count and ls_old is not initial.
          write'|'ls_old-dataat 86 '|'.
        endif.
        lv_count 0.
      endif.

    endif.

    ls_old pt_data.
    if lv_count > 0.
      continue.
    endif.

    uline (86).
    write'|''(Data)' hotspot,
             pt_data-tabname color col_heading hotspot,
             pt_data-fieldname color col_heading hotspot,
             at 86 '|'.
    write'|''      ',
             pt_data-tabtext(30color col_normal,
             pt_data-fieldtext(30color col_normal,
             at 86 '|'.

    lv_tabcount lv_tabcount + 1.

  endloop.

  if lv_count and ls_old is not initial.
    write'|''   'ls_old-dataat 86 '|'.
  endif.
  uline (86).


  describe table pt_data lines lv_lines.

  skip.
  "Format the output a little bit
  concatenate '$Found$' lv_lines '$records$in$' lv_tabcount '$tables' into lv_line.
  translate lv_line using '0 '.
  condense lv_line no-gaps.
  translate lv_line using '$ '.
  write/ lv_line.

  write.

  write' Done. '.

endform.                    " disp_data


*&---------------------------------------------------------------------*
*&      Form  build_fields
*&---------------------------------------------------------------------*
*If the user specified a table and field name, then use that to build up
*the datatype and other field parameters,
*----------------------------------------------------------------------*
form build_fields .

  datals_dd03l like dd03l.

  check p_tabnam is not initial and
        p_fieldn is not initial.

  select single from dd03l into ls_dd03l
        where tabname p_tabnam
        and   fieldname p_fieldn.

  check sy-subrc 0.

  refreshs_types_lengs_decs_doms_key.

  s_type-low ls_dd03l-datatype.
  s_type-sign 'I'.
  s_type-option 'EQ'.
  append s_type.

  s_leng-low ls_dd03l-leng.
  s_leng-sign 'I'.
  s_leng-option 'EQ'.
  append s_leng.

  s_dec-low ls_dd03l-decimals.
  s_dec-sign 'I'.
  s_dec-option 'EQ'.
  append s_dec.

  s_dom-low ls_dd03l-domname.
  s_dom-sign 'I'.
  s_dom-option 'EQ'.
  append s_dom.

  if ls_dd03l-keyflag abap_true.
    s_key-low ls_dd03l-keyflag.
    s_key-sign 'I'.
    s_key-option 'EQ'.
    append s_key.
  endif.

endform.                    " build_fields


*&---------------------------------------------------------------------*
*&      Form  goto_table
*&---------------------------------------------------------------------*
* Jump to the selected table
*----------------------------------------------------------------------*
form goto_table  using pv_pos
                       pv_line.

  datatabname      like dd03l-tabname,
        fieldname    like dd03l-fieldname,
        ls_gref      like tbprogref,
        progname     like rsvar-report,
        lv_dummy(10),
        lv_line(10),
        lt_sscr      like rsscr occurs with header line,
        ls_dd03l     like dd03l,
        ls_dd04l     like dd04l.

  datalt_params type table of rsparams,
        ls_param  type rsparams.



  split pv_line at space into lv_line lv_dummy tabname fieldname.
  condensetabnamefieldname.

  set parameter id 'DTB' field tabname.
  if pv_pos > 9.
    "The user wants to see the table and add more
    "selections to it
    call transaction 'SE16' and skip first screen.
    exit.
  endif.


  "User has selected the (Data) hotspot
  "See if we can plug the field name in via a parameter ID as well
  "so that we can go direct to the data instead of the data
  "selection screen
  select single from dd03l into ls_dd03l
             where tabname tabname
             and fieldname fieldname.
  if sy-subrc 0.
    select single from dd04l into ls_dd04l
            where rollname ls_dd03l-rollname
            and   domname ls_dd03l-domname.
    if sy-subrc and ls_dd04l-memoryid is not initial.
      set parameter id ls_dd04l-memoryid field p_data.
    endif.
  endif.

  select single from tbprogref into ls_gref
          where tabname tabname.
  if sy-subrc <> 0.
    "If we can't seem to find a program, then just
    "call the screen and let it sort the nonsense out
    call transaction 'SE16' and skip first screen.
  else.
    "Try to call the program manually with our additional
    "selection parameters
    concatenate '/1BCDWB/DB'  tabname into progname.

    load report progname part 'SSCR' into lt_sscr.

    refresh lt_params.
    loop at lt_sscr.
      if lt_sscr-dbfield cs fieldname.
        "Add our field to this selection
        ls_param-selname lt_sscr-name.
        ls_param-kind lt_sscr-kind.
        ls_param-option 'EQ'.
        ls_param-sign 'I'.
        "Put in all the fields we found in our earlier search
        loop at gt_tdata where tabname tabname
                        and fieldname fieldname.
          ls_param-low gt_tdata-data.
          append ls_param to lt_params.
        endloop.
      endif.
    endloop.

    "Display the data from the table directly the way
    "SE16 would
    call function 'RS_TABLE_LIST_CREATE'
      exporting
        table_name         tabname
      tables
        seltab             lt_params
      exceptions
        table_is_structure 1
        table_not_exists   2
        db_not_exists      3
        no_permission      4
        no_change_allowed  5
        others             6.
    if sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
*         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    endif.

  endif.


endform.                    " goto_table