Assigning abap что это

Assigning abap что это

To assign a data object to a field symbol, use the ASSIGN statement. The ASSIGN statement has several variants and parameters.

If you already know the name of the field that you want to assign to the field symbol when you write a program, use the static ASSIGN statement:

DATA: TEXT(20) TYPE C VALUE ‘Hello, how are you?’,
NUM TYPE I VALUE 5,
BEGIN OF LINE1,
COL1 TYPE F VALUE ‘1.1e+10’,
COL2 TYPE I VALUE ‘1234’,
END OF LINE1,
LINE2 LIKE LINE1.

Hello, how are you? has length 20

Static ASSIGN with Offset Specification

In a static assign statement, you can use positive offset and length specifications to assign a part of a field to a field symbol.

When you assign parts of fields to a field symbol, the following special conditions apply:

DATA: BEGIN OF LINE,
STRING1(10) VALUE ‘0123456789’,
STRING2(10) VALUE ‘abcdefghij’,
END OF LINE.

DATA: BEGIN OF LINE,
A VALUE ‘1’, B VALUE ‘2’, C VALUE ‘3’, D VALUE ‘4’,
E VALUE ‘5’, F VALUE ‘6’, G VALUE ‘7’, H VALUE ‘8’,
END OF LINE,
OFF TYPE I,
LEN TYPE I VALUE 2.

The example show how field symbols can make it easier to access and manipulate regular structures. Note, however, that this flexible method of manipulating memory contents beyond field limits also has its dangers and may lead to runtime errors.

If you do not know the name of the field that you want to assign to the field symbol when you write a program, you can use a dynamic ASSIGN statement:

At runtime, the system searches for the corresponding data object in the following order:

If the search is successful and a field can be assigned to the field symbol, SY-SUBRC is set to 0. Otherwise, it is set to 4, and the field symbol remains unchanged. For security reasons, you should always check the value of SY-SUBRC after a dynamic ASSIGN to prevent the field symbol pointing to the wrong area.

Searching for the field in this way slows down the program. You should therefore only use the dynamic ASSIGN statement when absolutely necessary. If you know when you create the program that you want to assign a table work area to the field symbol, you can also use the following variant of the dynamic ASSIGN statement:

The system then only searches within the table work areas in the main program of the current program group for the data object that is to be assigned to the field symbol.

Suppose we have three programs. The main program:

PROGRAM DEMO.
TABLES SBOOK.
SBOOK-FLDATE = SY-DATUM.
PERFORM FORM1(MYFORMS1).

and two other programs:

PROGRAM MYFORMS1.
FORM FORM1.
PERFORM FORM2(MYFORMS2).
ENDFORM.

The program group in the internal session now consists of the programs DEMO, MYFORMS1 and MYFORMS2. The field symbol is defined in MYFORMS2. After the dynamic ASSIGN statement, it points to the component FLDATE of the table work area SBOOK declared in the main program DEMO.

DATA: NAME1(20) VALUE ‘SBOOK-FLDATE’,
NAME2(20) VALUE ‘NAME1’.

In the first ASSIGN statement, the system finds the component FLDATE of the table work area SBOOK and SY-SUBRC is set to 0. In the second ASSIGN statement, the system does not find the field NAME1 because it is declared by the DATA statement and not by the TABLES statement. In this case, SY-SUBRC is set to 4.

Assigning Field Symbols

Instead of using the names of data objects, you can also assign field symbols to field symbols in all variants of the ASSIGN statement.

in a static ASSIGN and:

DATA: BEGIN OF S,
A VALUE ‘1’, B VALUE ‘2’, C VALUE ‘3’, D VALUE ‘4’,
E VALUE ‘5’, F VALUE ‘6’, G VALUE ‘7’, H VALUE ‘8’,
END OF S.

points to S-A, OFF is zero, and S-A is assigned to

points to S-A, OFF is one, and S-B is assigned to

points to S-B, OFF is two, and S-D is assigned to

points to S-D, OFF is three, and S-G is assigned to

Assigning Components of Structures to a Field Symbol

For a structured data object , you can use the statement

This statement is particularly important for addressing components of structured data objects dynamically. If you assign a data object to a field symbol generically, or pass it generically to the parameter interface of a procedure, you cannot address its components either statically or dynamically. Instead, you must use the above statement. This allows indirect access either using the component name or its index number.

DATA: BEGIN OF LINE,
COL1 TYPE I VALUE ’11’,
COL2 TYPE I VALUE ’22’,
COL3 TYPE I VALUE ’33’,
END OF LINE.

DATA COMP(5) VALUE ‘COL3’.

Defining the Data Type of a Field Symbol

To set the data type of a field symbol independently of that of the objects that you assign to it, use the TYPE addition in the ASSIGN statement:

There are two possible cases:

Using the TYPE option with a typed field symbol makes sense if the data type of the data object to be assigned is incompatible with the typing of the field symbol, but you want to avoid the resulting error message. In this case, the specified type and the typing of the field symbol must be compatible. The field symbol then retains its data type, regardless of the assigned data object.

A runtime error occurs if

DATA TXT(8) VALUE ‘19980606’.

DATA MYTYPE(1) VALUE ‘X’.

In this example, the character string TXT is assigned to three times. In the first assignment, the type is not specified. The second time, the type is specified as D, and finally as X. The format of the second output line depends on the settings of the current user in their user master record. The numbers in the last line are the hexadecimal codes of the characters in TXT. They are platform-specific (in this case, ASCII).

Data Areas for Field Symbols

You can only assign data objects from the data areas of the ABAP program to a filed symbol. When you assign a data object to a field symbol, the system checks at runtime to ensure that no data is lost due to the field symbol addressing memory outside the data area.

The data areas of an ABAP program are:

Field symbols cannot point to addresses outside these areas. If you assign data objects to a field symbol and point to addresses outside these areas, a runtime error occurs.

Certain system information, such as the control blocks of internal tables, is also stored in the DATA storage area. Therefore, despite the runtime checks, you may unintentionally overwrite some of these fields and cause subsequent errors (for example, destruction of the table header).

DATA: TEXT1(10), TEXT2(10), TEXT3(5).

After starting DEMO, a runtime error occurs. The short dump message begins as follows:

The DATA memory area is at least 25 bytes wide (it can be expanded due to alignment of the data areas in memory). In one of the loop passes, the program tries to access an address outside this area. The termination message also contains the contents of the field SY-INDEX, which may be different from case to case. Up to the 24th loop pass, no error occurs. If you replace TEXT1 with TEXT2 in the ASSIGN statement, the error occurs ten loop passes earlier.

Источник

Assigning abap что это

SAP NetWeaver AS ABAP Release 751, ©Copyright 2017 SAP AG. All rights reserved.

Field Symbols, ASSIGN INCREMENT

The examples shows how the statement ASSIGN behaves when the addition INCREMENT is used.

CLASS demo DEFINITION.
PUBLIC SECTION.
CLASS-METHODS main.
ENDCLASS.

CLASS demo IMPLEMENTATION.
METHOD main.
DATA assign TYPE c LENGTH 1 VALUE ‘1’.
cl_demo_input=>request(
EXPORTING text = `ASSIGN statement (1 to 6)`
CHANGING field = assign ).

DATA: BEGIN OF struc,
word TYPE c LENGTH 4 VALUE ‘abcd’,
int1 TYPE i VALUE 111,
int2 TYPE i VALUE 222,
stri TYPE string VALUE `efgh`,
END OF struc.

FIELD-SYMBOLS: LIKE struc-word,
TYPE i.

CASE assign.
WHEN ‘1’. «-> sy-subrc 0
ASSIGN struc-word INCREMENT 1 TO RANGE struc.
WHEN ‘2’. «-> Runtime error
ASSIGN struc-word INCREMENT 1 TO RANGE struc.
WHEN ‘3’. «-> Runtime error
ASSIGN struc-word INCREMENT 2 TO RANGE struc.
WHEN ‘4’. «-> Runtime error
ASSIGN struc-word INCREMENT 2 TO RANGE struc.
WHEN ‘5’. «-> sy-subrc 4
ASSIGN struc-word INCREMENT 3 TO RANGE struc.
WHEN ‘6’. «-> sy-subrc 4
ASSIGN struc-word INCREMENT 3 TO RANGE struc.
WHEN OTHERS.
cl_demo_output=>display( ‘Enter a number between 1 and 6’ ).
RETURN.
ENDCASE.

cl_demo_output=>write( |sy-subrc: < sy-subrc >| ).
IF IS ASSIGNED OR IS ASSIGNED.
cl_demo_output=>write( ‘Field symbol is assigned’ ).
ENDIF.
cl_demo_output=>display( ).
ENDMETHOD.
ENDCLASS.

This example shows why use the addition INCREMENT in the statement ASSIGN should be used only if it is necessary access sequences of similar memory areas and that the typing of the field symbol must match the way casting_spec is specified. Any access which is not appropriate as shown in the example can produce the following behavior:

Источник

ABAP Blog

Все о разработке в решениях от SAP

ABAP Blog

Все о разработке в решениях от SAP

Ссылки

Цитаты

Самым важным отличием хорошо спроектированного модуля от плохо спроектированного является степень, в которой модуль скрывает свои внутренние данные и другие детали реализации от других модулей.

Джошуа Блох

Новое

Последние комментарии

Динамическое программирование в ABAP

Assigning abap что это. Смотреть фото Assigning abap что это. Смотреть картинку Assigning abap что это. Картинка про Assigning abap что это. Фото Assigning abap что это

На днях довелось прослушать курс BC402 в рамках программы «Вечерний ABAP», хочется выразить благодарность компании SAP за такую возможность, а также отметить профессионализм преподавателя, в роли которого выступал Василий Ковальский. Сам курс посвящен обзору довольно обширных тем, которые, так или иначе, пригодятся всем ABAP программистам в их повседневной деятельности. Одной из рассматриваемых тем данного курса была возможность динамического программирования в ABAP, о которой и хотелось бы поговорить далее.

Ключевой особенностью программного обеспечения является его способность к изменению и приспособлению к меняющимся условиям. Одним из инструментов обеспечивающих такое приспособление является динамическое программирование.

В ABAP под динамическим программированием могут пониматься следующие вещи:

В данной статье будут рассмотрены последние 2 способа, информацию по остальным можно получить из официальной справки, а также из курса BC402.

Для динамического программирования необходимо понять, что такое ссылочные переменные и указатели на поля (field symbols) и в чем их отличия.

Для разработчиков, только начинающих изучение ABAP термин field-symbols часто может вызывать путаницу. Те из них, кто работал с языками C/C++, зачастую путают их с типом указателя (Pointer). Но field-symbols не являются указателями на область памяти, они лишь являются указателями на переменную или объект данных которые являются видимыми в текущем блоке кода (можно использовать термин alias).

На следующем рисунке хорошо видны основные отличия.

Assigning abap что это. Смотреть фото Assigning abap что это. Смотреть картинку Assigning abap что это. Картинка про Assigning abap что это. Фото Assigning abap что это

У нас есть три объекта:

Обобщенные типы

В дополнение к стандартным типам данных, в ABAP существует так же ряд обобщенных типов, использование которых возможно только в случае: формальных параметров методов (функций, процедур), field-symbols и ссылочных переменных. Часто используя динамическое программирование, приходится иметь дело с заранее не известными типами данных, для этого нужно знать каким образом их можно представить в виде обобщенных типов.

Перечень таких типов определен ниже:

ТипОписание
anyЛюбой тип данных
any tableЛюбая внутренняя таблица
clikeОбобщенный символьный тип (c, d, n, t, string, а так же плоские структуры, состоящие из элементов символьных типов)
csequenceТекстовая последовательность (c, string)
dataЛюбой тип данных (аналогично any в случае объявления TYPE data, если объявлять TYPE REF TO DATA, будут подразумеваться ссылки на данные, но не объектные ссылки). Данный тип может быть использован в ссылочных переменных (рассмотрено ниже).
decfloatЧисловой тип с плавающей запятой, один из следующих: decfloat16, decfloat34.
hashed tableЛюбая хеш таблица
index tableЛюбая стандартная или сортированная внутренняя таблица.
numericЧисловой тип (i (b, s), p, decfloat16, decfloat34, f)
objectЛюбой объектный тип
simpleЛюбой элементарный тип данных включая плоские структуры состоящие из символьных элементов.
sorted tableЛюбая сортированная таблица
standard tableЛюбая стандартная таблица
tableАналогично предыдущему
xsequenceБайтовая последовательность (x, xstring)

Предположим мы пишем некую процедуру, в параметрах которой хотели бы видеть любую сортированную или стандартную таблицу, сделать это можно с помощью обобщенного типа index table:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *