SAP R/3 форум ABAP консультантов
Russian ABAP Developer's Club

Home - FAQ - Search - Memberlist - Usergroups - Profile - Log in to check your private messages - Register - Log in - English
Blogs - Weblogs News

Таблица как параметр в подпрограмме



 
Post new topic   Reply to topic    Russian ABAP Developer's Club Forum Index -> ABAP
View previous topic :: View next topic  
Author Message
avalon
Участник
Участник



Joined: 31 Jul 2008
Posts: 6
Location: Украина

PostPosted: Mon Feb 23, 2009 3:32 pm    Post subject: Таблица как параметр в подпрограмме Reply with quote

Есть три таблицы у которых есть одинаковое поле как по типу так и по имени. Необходимо выполнить однотипные манипуляции, как то выбрать максимальное значение поля в таблице. Хочу оформить это формой, но что то не получается, не могло бы уважаемое сообщество подсказать? Аля такое:

Code:

form get_max tables p_table type standart table
                               p_max type calc_line.

sort p_table by acpos destending.

read table p_table index 1.

move p_table-acpos to p_max.


endform


Вот только так нельзя. Ругается что не знает структуры p_table.
Back to top
View user's profile Send private message
ghost
Специалист
Специалист


Age: 37
Joined: 18 Jan 2008
Posts: 71
Location: Tashkent-Astana-Moscow

PostPosted: Mon Feb 23, 2009 9:20 pm    Post subject: Reply with quote

Здесь вам поможет динамическое программирование. используйте динамическое определение таблиц и полей структур в вашей форме конструкцией assign и assign component .. of structure ..

P.S. Кстати на форуме целая отдельная ветка выделена по динамическому программированию, может что оттуда подчерпнете Smile

_________________
Пользователь не знает, чего он хочет, пока не увидит то, что он получил. (Э. Йодан)
Back to top
View user's profile Send private message Send e-mail Blog
vga
Мастер
Мастер


Age: 180
Joined: 04 Oct 2007
Posts: 1218
Location: Санкт-Петербург

PostPosted: Tue Feb 24, 2009 12:22 pm    Post subject: Reply with quote

Может и заблуждаюсь, но способа сделать сортировку внутри подпрограммы без создания неполной копии таблицы не нахожу. Интересно было бы увидеть решение.
Back to top
View user's profile Send private message Blog Visit poster's website
ghost
Специалист
Специалист


Age: 37
Joined: 18 Jan 2008
Posts: 71
Location: Tashkent-Astana-Moscow

PostPosted: Tue Feb 24, 2009 1:01 pm    Post subject: Reply with quote

Code:
report ztest.

data: begin of tab1 occurs 0,
        col1(4)  type c,
        col2(10) type c,
      end of tab1.

start-of-selection.
  tab1-col1 = 'C'.
  append tab1.
  tab1-col1 = 'B'.
  append tab1.
  tab1-col1 = 'A'.
  append tab1.
  data: max(4) type c.
  perform get_max using 'TAB1'
                      'COL1'
                changing max.

form get_max using u_tab_name
                 u_field_name
           changing c_value.

  data: l_tab_name(132) type c,
        lref type ref to data,
        lt_sort_tab  type abap_sortorder_tab,
        ls_sort_line type abap_sortorder.

  field-symbols: <lfs_t_tab> type standard table,
                 <lfs_s_struc>,
                 <lfs_field>.

  concatenate u_tab_name '[]' into l_tab_name.

  assign (l_tab_name) to <lfs_t_tab>.
  check <lfs_t_tab> is assigned.

  try.
      create data lref
        like line of <lfs_t_tab>.
      assign lref->* to <lfs_s_struc>.
    catch cx_sy_create_data_error.
      message 'Create data error ! ' type 'E'.
  endtry.

  ls_sort_line-name = u_field_name.
  append ls_sort_line to lt_sort_tab.

  try.
      sort <lfs_t_tab> by (lt_sort_tab).
    catch cx_sy_dyn_table_ill_comp_val.
      message 'Wrong field' type 'E'.
  endtry.

  read table <lfs_t_tab>
    assigning <lfs_s_struc>
    index 1.
  if sy-subrc eq 0.
    assign component u_field_name
      of structure <lfs_s_struc> to <lfs_field>.
    check <lfs_field> is assigned.

    c_value = <lfs_field>.
  endif.
endform.                 


P.S. так что передавая название таблицы и поля, можно получить максимальное значение по этому полю (ну или минимальное смотря как сортировать)

_________________
Пользователь не знает, чего он хочет, пока не увидит то, что он получил. (Э. Йодан)
Back to top
View user's profile Send private message Send e-mail Blog
vga
Мастер
Мастер


Age: 180
Joined: 04 Oct 2007
Posts: 1218
Location: Санкт-Петербург

PostPosted: Tue Feb 24, 2009 1:43 pm    Post subject: Reply with quote

Да, гуд. В 4.6 с небольшими переделками пошло.
Back to top
View user's profile Send private message Blog Visit poster's website
avalon
Участник
Участник



Joined: 31 Jul 2008
Posts: 6
Location: Украина

PostPosted: Tue Feb 24, 2009 1:46 pm    Post subject: Reply with quote

Может кому поможет, но пока не отвечали, придумал макросом это решить

Code:

define macros_get_max.

sort &1 by acpos destending.

read table &1 index 1.

move &1-acpos to &2.

end-of-difinition.


P.S. Правда макросы к сожалению отладить невозможно. Crying or Very sad
Back to top
View user's profile Send private message
DKiyanov
Участник
Участник


Age: 48
Joined: 12 Jan 2009
Posts: 17
Location: Хабаровск

PostPosted: Thu Feb 26, 2009 5:34 pm    Post subject: Reply with quote

Возможно я немного старомоден и это не самый производительный вариат, зато простой.
Code:

perform get_max tables tab1 using tab1-a max_fld1.
perform get_max tables tab2 using tab1-a max_fld2.
perform get_max tables tab3 using tab1-a max_fld3.

form get_max tables tab using fld max_fld.
  loop at tab.
    if sy-tabix = 1 or max_fld < fld.
      max_fld = fld.
    endif.
  endloop.
endform.

примечание:
таблицы tab1, tab2, tab3 должны быть с заголовком (что ныне не модно)
параметр подпрограммы fld фактически является ссылкой на поле заголовка по которому идёт поиск, в результате когда выполняется loop по таблице меняется заголовок и соответственно значение в fld

PS не заметил сразу что автор хотел сделать поиск именно с сортировкой
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    Russian ABAP Developer's Club Forum Index -> ABAP All times are GMT + 4 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


All product names are trademarks of their respective companies. SAPNET.RU websites are in no way affiliated with SAP AG.
SAP, SAP R/3, R/3 software, mySAP, ABAP, BAPI, xApps, SAP NetWeaver and any other are registered trademarks of SAP AG.
Every effort is made to ensure content integrity. Use information on this site at your own risk.