Sappress Abap An Introduction
Sappress Abap An Introduction
Index
The Authors
www.sap-press.com/4955
Chapter 12
Working with Dates, Times,
Quantities, and Currencies
This chapter explains how to handle business data that represents date
and time, quantities in different units of measure, and amounts in differ-
ent currencies.
12.1 Dates
In this section, we’ll cover the details on how the date type (d) works and
some different ways to use dates in ABAP programs. Chapter 3 introduced
the date data type (d), showing how to define a date and that it is stored in a
YYYYMMDD format where the first four digits represent the year, the sec-
ond two represent the month, and last two represent the day.
465
12 Working with Dates, Times, Quantities, and Currencies 12.1 Dates
Listing 12.1 Using SUBSTRING to Get Year, Month, and Day Because 2020 is a leap year, the same operation results in a different date
(March 11 instead of March 12), as shown in Figure 12.1.
The code in Listing 12.1 can be used regardless of the user’s date format pref-
12
erences; the value when working with the date data type will always be the
same.
Adding/subtracting Adding days to a date data type can be done by adding an integer to the
days date; the date data type will handle updating the day, month, and year val- Figure 12.1 Result of Date Calculation in Regular versus Leap Year
ues, as shown in Listing 12.2, in which the new date is February 6, 2019.
Adding a month to a date is not as easy. If you want to add a month to your Adding months to
DATA: my_date TYPE d VALUE ‘20190102’.
date, you can call the RP_CALC_DATE_IN_INTERNAL function module shown in a date
my_date = my_date + 35.
Listing 12.5, which will change the date from January 1, 2019, to February 1,
Listing 12.2 Adding 35 Days to January 2, 2019 2019.
You can also subtract days from a date variable in a similar fashion. In the DATA: my_date TYPE d VALUE ‘20190101’.
example shown in Listing 12.3, the result will be January 2, 2019.
466 467
12 Working with Dates, Times, Quantities, and Currencies 12.1 Dates
Other date Dates also can be compared using the regular comparison operators, such days cannot be calculated. The example in Listing 12.7 demonstrates this
operations as < or >=. The example in Listing 12.6 will always return “True” because effect.
you’re adding 1 to the date and then comparing the result. If you change the
DATA: my_integer TYPE i,
sign from + to - in this example, it will always return “False”.
my_date TYPE d.
DATA: one_date TYPE d VALUE '20190801', my_date = ‘20190230’.
another_date TYPE d. my_integer = my_date.
IF my_integer = 0.
another_date = one_date + 1. WRITE: / 'Date is invalid'.
IF another_date > one_date. ENDIF.
WRITE: 'True'.
Listing 12.7 Assigning Invalid Date to Integer Variable
ELSE.
WRITE: 'False'.
ENDIF. 12.1.2 Factory Calendars
Listing 12.6 Comparing Dates There may be a situation in which you need to write a program that will act
differently based on which days are working days for a given company. Fac- 12
Date variables are quite amazing in ABAP: you can use string functions with tory calendar days will take into account any public holidays and any rele-
them just like with any character type variables, yet you can perform calcu- vant working days, allowing you to complete date calculations based on the
lations with them, just like with the numeric fields. number of actual working days.
But this versatility can sometimes tempt ABAP developers to cut corners Factory calendars are client-independent and typically are created for each Viewing factory
and underestimate the complexity of the task. For example, one might relevant country or region in which a company operates. This allows for a calendars
think: Instead of using a bulky function to add a month to a date, couldn’t factory calendar to incorporate the local public holiday schedule. To view
we just derive the month value (just like we did in Listing 12.1), add 1 to it, all of the calendars in an ABAP system, enter Transaction SCAL, select the
and be done? Factory Calendar radio button, and click the Display button , as pic-
The developers who attempt this quickly realize that when dealing with a tured in Figure 12.2.
date in December they also need to consider the year change. After adding
an IF… condition to increase the year as well, a developer could be very
pleased with the result. It might take several months before worried users
start asking why they’re seeing the date February 30 on their screens.
This brings us to the next point: it’s feasible to assign an incorrect date to
such a variable, and this will not cause a runtime error. There are various
ways to test date validity; using the DATE_CHECK_PLAUSIBILITY function
module is one of them. But there is also an interesting approach that
exploits the fact that when a variable of type d contains an invalid date and
is assigned to a variable of type i (integer), the value of the integer variable
becomes 0. This is because integer presentation of a date is the number of
days since the beginning of SAP time, and for an invalid date the number of
Figure 12.2 Initial Screen for Transaction SCAL
468 469
12 Working with Dates, Times, Quantities, and Currencies 12.1 Dates
In the next screen, you’ll see a list of the factory calendars defined in the
system. These are usually based on country or region and will have Valid
From and Valid To dates. Select the calendar you’re interested in viewing
(USA in this example) and click the Calendar button, as shown in Figure 12.3.
Next, select a relevant year for the calendar that you want to view and click
the Year button, as shown in Figure 12.4.
Figure 12.5 Viewing Working/Nonworking Days and Public Holidays for Factory
Calendar
Now that you understand what a factory calendar is and how to set one up, Converting
you can use factory dates in your ABAP code with the help of some standard factory dates
function modules.
Figure 12.4 Selecting Calendar Year in Transaction SCAL
Use function module DATE_CONVERT_TO_FACTORYDATE to convert a regular
date into a factory date. The factory date will be a number representing the
Now you’ll see a calendar display for the selected year, showing which days
number of working days since the factory calendar began. If you convert a
are considered working days and which days are nonworking days, includ-
date that isn’t a working day, the next working day will be used.
ing a list of public holidays for the year (Figure 12.5).
You can then perform some calculations using the factory date and convert
it back to a calendar date using the FACTORYDATE_CONVERT_TO_DATE function
module. An example of this is shown in Listing 12.8, which calculates a date
10 working days in the future.
470 471
12 Working with Dates, Times, Quantities, and Currencies 12.1 Dates
472 473
12 Working with Dates, Times, Quantities, and Currencies 12.1 Dates
Datum formatting Instead of using the d date type, you can use the datum date type, which will 12.1.4 System Date Fields
be displayed per the style of the user’s date preference any time it’s dis-
There are three system date fields: sy-datum, sy-datlo, and sy-fdayw. All
played to the user (see Listing 12.9 and the resulting output shown in Figure
these system dates return values related to the current date. sy-datum
12.7).
returns the current system date. The system date is dependent on the sys-
DATA: my_datum TYPE datum VALUE '20190801'. tem’s current time zone. If you’re concerned about the date for the logged
WRITE: 'Type DATUM:', my_datum. in user’s time zone, you can use sy-datlo. Finally, sy-fdayw will return the
factory day of week as an integer, meaning 0 for Sunday and 6 for Saturday.
DATA: my_date TYPE d VALUE '20190801'.
These system date fields can all be directly assigned to valid variables and
WRITE: /'Type D:', my_date.
can also be used in the variable declaration, as shown in Listing 12.10.
Listing 12.9 Demonstrating Date Type Differences
DATA: today type sy-datum,
today_local type sy-datlo,
factory_day TYPE sy-fdayw.
today = sy-datum.
12
today_local = sy-datlo.
Figure 12.7 Output ofListing 12.9 factory_day = sy-fdayw.
valid. There are many reasons that a table may contain date-limited
records; for example, a table may contain promotional discounts that are
only valid between two dates, or a table containing an employee’s position
in the company may be date-limited so that it can contain all current and
past positions.
Often, you don’t know when a record will no longer be valid, in which case
the valid_to date will be set to the latest date possible, which is December
Figure 12.8 User’s Date and Time Preferences 31, 9999. An HR record displaying an employee’s current position would
have a valid_to date like that; if the employee’s position changes, the
It’s better to use the datum data type in your program instead of the d data valid_to date is updated to show the last day at that position.
type whenever you’ll be displaying a date to the user. The datum and d date Selecting a date-limited record valid today is easy. First, determine if you
types can be used interchangeably in your code; the underlying data will be will be using the system date (sy-datum) or the local date (sy-datlo).
exactly the same.
474 475
12 Working with Dates, Times, Quantities, and Currencies 12.2 Times
In the following example, we’ll select a record from user table USR02, which 12.2 Times
has optional Valid From and Valid To fields, as shown in Figure 12.9.
In this section, we’ll cover how the time data type (t) works and some addi-
tional functions for calculating time, as well as other time data types. Chap-
ter 3 introduced the time data type (t), and that time is stored with two
characters for hours, two characters for minutes, and two characters for sec-
onds, in the format HHMMSS.
If you need time that is more exact than seconds, you can also use a time-
stamp, which will be covered in this section. A timestamp will calculate
time to the precision of 100 nanoseconds (ns), which is seven decimal
places, and will also include the date. The timestamp format is YYYYMMD-
Figure 12.9 Table USR02 with Valid from and Valid to Fields DHHMMSS.SSSSSSS.
Using dates To select only the records that have a limited validity and are valid for
in SELECT today, you need to select records with a valid from date less than or equal to
12.2.1 Calculating Time
12
today and a valid to date greater than or equal to today. For this example, Just as with dates, you can compare time using the regular comparison
the valid from field is GLTGV and the valid to field is GLTGB, as shown in Lis- operators and calculate time using regular math expressions. The example
ting 12.11, which will only return the record for user BGRFC_SUPER. in Listing 12.12 creates two variables of type t and fills in one of them with
the current system time using the sy-uzeit system field. Then the number
“New Open SQL
5 is added to that variable and placed in the another_time variable. At the
SELECT *
end, the variable values are compared for equality.
FROM USR02
INTO TABLE @DATA(results) DATA: one_time TYPE t,
WHERE GLTGV <= @sy-datum another_time TYPE t.
AND GLTGB >= @sy-datum.
one_time = sy-uzeit.
“old Open SQL WRITE: / 'Current time:', one_time.
DATA: results TYPE STANDARD TABLE OF USR02.
SELECT * another_time = one_time + 5.
FROM UR02 WRITE: / 'Current time + 5:', another_time.
INTO TABLE results
WHERE GLTGV <= sy-datum IF one_time = another_time.
AND GLTGB >= sy-datum. WRITE: / 'Time is the same'.
ELSE.
Listing 12.11 Selecting Record Valid for Today
WRITE: / 'Time is different'.
ENDIF.
476 477
12 Working with Dates, Times, Quantities, and Currencies 12.2 Times
Figure 12.10 shows an example of executing this program. Note that calcu- GET TIME STAMP FIELD my_timestampl.
lations with time occur in seconds; therefore, adding the number 5 to a GET TIME STAMP FIELD data(my_inline_timestamp).
time variable adds five seconds as a result.
Listing 12.13 GET TIME STAMP FIELD
The regular comparison operators can only be used between two time- Comparing
stamps, not between a timestamp and a date or time. The comparisons will timestamps
478 479
12 Working with Dates, Times, Quantities, and Currencies 12.2 Times
You can also perform a reverse operation and convert a local date and time Table 12.1 Timestamp Formats for String Templates
into a timestamp using the CONVERT INTO TIMESTAMP function. A DATE and
TIME ZONE are both required when using this function, but the TIME and
The syntax to use these different timestamp formats is simple. Within the
DAYLIGHT SAVING TIME variables are optional. An example converting the
string template, between the curly braces you put the timestamp variable
results from Listing 12.15 back into a timestamp is shown in Listing 12.17.
name followed by TIMESTAMP = and then any of the formats listed in Table
Remember that the time zone passed is used to convert the local date and
12.1. The example shown in Listing 12.18 will return 2019-01-01T12:00:
time from that time zone into a UTC time zone.
00.0000000.
CONVERT DATE my_pst_date
DATA: unformatted TYPE timestampl
TIME my_pst_time
VALUE '20190101120000.0000000'.
DAYLIGHT SAVING TIME my_dst
DATA(my_string) = |{ unformatted TIMESTAMP = ISO }|.
INTO TIME STAMP my_utc TIME ZONE ‘PST’.
Listing 12.18 Setting Timestamp Format from within String Template
Listing 12.17 Converting PST Date and Time to UTC Timestamp
You also can convert the time used in the string template to reflect a given
Timestamp When outputting timestamps to a string template, there are special format-
time zone by adding TIMEZONE = followed by the desired time zone, as
formatting ting options that can be applied to display the timestamp in a more user-
shown in Listing 12.19, which will return 2019-01-01T04:00:00.0000000.
friendly format. Table 12.1 provides a list of all the possible formatting
options. my_string = |{ unformatted TIMESTAMP = ISO
TIMEZONE = 'PST' }|.
Listing 12.19 Setting Timestamp Output and Time Zone for Output in String
Template
480 481
12 Working with Dates, Times, Quantities, and Currencies 12.3 Quantities
There are some additional timestamp-related functions that use the CL_ You can see the different possible units of measure that are set up in your Display units of
ABAP_TSTMP system class. This class should be used if you want to add or sub- ABAP environment by entering Transaction CUNI, shown in Figure 12.11. measure
tract seconds from a timestamp, calculate the difference between two time- From there, select a dimension such as Length from the dropdown, and
stamps, or convert a long timestamp to a short timestamp or vice versa. click Units of Measurement.
Listing 12.20 Declaring and Getting System Time and Local Time Data
12.3 Quantities
Quantitative fields are used in SAP ERP systems to track and convert the
results of different types of measurements, ranging from lengths (e.g.,
meters and inches) to masses (e.g., grams and pounds) and units of packag-
ing (e.g., box and pallet). These fields are always associated with a unit of
Figure 12.12 List of Length Units of Measurement from Transaction CUNI
measure (UOM), which allows for converting the quantitative values from
one unit to another.
482 483
12 Working with Dates, Times, Quantities, and Currencies 12.3 Quantities
from and a unit to convert to. This function module will also round results
Figure 12.13 Table Containing Quantity and Unit of Measure if necessary, and you can optionally pass in a + or – to force it to round up or
down. Listing 12.21 demonstrates converting a quantity of 5 from meters (M)
Next, click the Currency/Quantity Fields tab, and you’ll see that only the to centimeters (CM). The unit of measure used can also be seen in the length
QUANTITY field has an editable row. From here, you can add a reference to units of measure list in Figure 12.12.
the table and field that will describe the quantity’s unit. For this example, DATA: my_quantity TYPE i VALUE 5.
enter the current table, “ZQUANTITY”, and the field, “UNIT_OF_MEASURE”, CALL FUNCTION 'UNIT_CONVERSION_SIMPLE'
as pictured in Figure 12.14. Assigning a corresponding unit of measure field EXPORTING
for any quantity data type is required to activate the table. input = my_quantity
Because you store the quantity and unit in the same table, different records unit_in = 'M'
can have data stored in different quantities. unit_out = 'CM'
IMPORTING
It’s possible to store the unit of measure in one table and reference it within output = my_quantity
a quantity in another table, if this is required by your business rules. In this EXCEPTIONS
case, you would enter a different table name in the Reference Table field in conversion_not_found = 1
Transaction SE11. division_by_zero = 2
484 485
12 Working with Dates, Times, Quantities, and Currencies 12.4 Currencies
input_invalid = 3 The SAP ERP currency codes are listed in the Currency column and corre-
output_invalid = 4 sponding ISO currency codes in the ISO column. Note that even though
overflow = 5 most SAP currency codes match the ISO standard, there could be some-
type_invalid = 6 times multiple internal SAP codes for one ISO currency code.
units_missing = 7
When converting amounts across different currencies, the current
unit_in_not_found = 8
exchange rate can be found in Transaction OB08. Because exchange rates
unit_out_not_found = 9
others = 10 regularly change, it’s possible to have the exchange rates in your system
. automatically updated on a daily or weekly basis, which is a topic outside
IF sy-subrc <> 0. the scope of this book. Figure 12.16 shows that the currency exchange rate
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno between the US dollar and the euro is 0.94 euros to 1 US dollar.
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
WRITE: my_quantity.
ment MANDT, field ID with data element INTEGER, field PRICE with data ele-
ment PREIS (type CURR), and field CURRENCY with data element USRCUKY (type
CUKY). If some of the data elements don’t look familiar, don’t worry: they’re
standard SAP data types that should exist in any ABAP system.
486 487
12 Working with Dates, Times, Quantities, and Currencies 12.4 Currencies
Figure 12.17 Table ZCURRENCY Using Currency Data Types DATA: local_amount TYPE P DECIMALS 2.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
Figure 12.18 Currency/Quantity Fields Tab for Table ZCURRENCY
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
Because you have a field for currency in the table, each record in the table
can have any currency denomination. And just like with quantity fields, Listing 12.22 Currency Conversion
you also can reference the currency key in another table.
488 489
12 Working with Dates, Times, Quantities, and Currencies 12.5 Updating the Shopping Cart Example
490 491
12 Working with Dates, Times, Quantities, and Currencies 12.5 Updating the Shopping Cart Example
populated, as shown in Figure 12.23. Click the Activate button to activate the
data element.
Currency data Next, return to Transaction SE11, select the Data Type radio button, enter
element “ZPRODUCT_CURRENCY” in the corresponding textbox, and click the Cre- Figure 12.23 ZPRODUCT_CURRENCY Field Label Settings
ate button. Select the Data Element radio button in the Data Type popup
12
and click the continue button. Next, return to Transaction SE11, select the Data Type radio button, enter UOM data element
In the Change Data Element screen, enter “Product Currency for Shopping “ZPRODUCT_UOM” in the corresponding textbox, and click the Create but-
Cart Example” in the Short Description textbox. Then, with the Data Type ton. Select the Data Element radio button in the Data Type popup and click
tab selected, choose the Elementary Type radio button and the Built-in Type the Continue button.
radio button. In the Data Type field, use the input help dropdown and select In the Change Data Element screen, enter “Product UOM for the Shopping
the CUKY type. The Length field will be automatically set to 5. Your data ele- Cart Example” in the Short Description textbox. Then, with the Data Type
ment should look like the one pictured in Figure 12.22. tab selected, choose the Elementary Type radio button and the Built-in Type
radio button. Enter the Data Type “UNIT” and Length “3”. Your data element
should look like the one pictured in Figure 12.24.
Next, select the Field Label tab and enter “Currency” for all Field Label text- Figure 12.24 ZPRODUCT_UOM Data Type Settings
boxes. Then press (Enter) and the Length textboxes will be automatically
492 493
12 Working with Dates, Times, Quantities, and Currencies 12.5 Updating the Shopping Cart Example
Next, select the Field Label tab and enter “Unit” for the Short Field Label text
box and “Unit of Measure” for all other Field Label textboxes. Then press
(Enter) and the Length textboxes will be automatically populated, as
shown in Figure 12.25. Click the Activate button to activate the data ele-
ment.
12
Quantity data Next, return to Transaction SE11, select the Data Type radio button, enter
element “ZCART_QUANTITY” in the corresponding textbox, and click the Create
button. Select the Data Element radio button in the Data Type popup and
click the Continue button.
In the Change Data Element screen, enter “Cart Quantity for the Shopping Figure 12.27 ZCART_QUANTITY Field Label Options
Cart Example” in the Short Description textbox. Then, with the Data Type
tab selected, choose the Elementary Type radio button and the Built-in Type Now that you’ve created the new data elements, let’s update the transpar- Updating table
radio button. Enter the Data Type “QUAN”, Length “13”, and Decimal Places ent tables that use those data elements. First, update transparent table ZPRODUCT
“3”. Your data element should look like the one pictured in Figure 12.26. ZPRODUCT. To do this, go back to Transaction SE11, select the radio button for
Next, select the Field Label tab and enter “Quantity” for all the Field Label Database Table, and enter “ZPRODUCT” in the corresponding textbox.
textboxes. Then press (Enter) and the Length textboxes will be automati- Then press the Change button.
cally populated, as shown in Figure 12.27. Click the Activate button to acti- With the Fields tab selected, add Field “PRICE” with Data element “ZPRO-
vate the data element. DUCT_PRICE”, Field “CURRENCY” with Data element “ZPRODUCT_CUR-
RENCY”, and Field “UOM” with Data element “ZPRODUCT_UOM”, as shown
in Figure 12.28.
494 495
12 Working with Dates, Times, Quantities, and Currencies 12.5 Updating the Shopping Cart Example
Now, select the Currency/Quantity Fields tab and enter Reference Table
Next, select the Currency/Quantity Fields tab and enter Reference Table
“ZPRODUCT” and Reference Field “UOM” for Field “Quantity”. This will set
“ZPRODUCT” and Reference Field “CURRENCY” for the Field “PRICE”, as
the UOM field in table ZPRODUCT as the unit for the QUANTITY field in this table,
shown in Figure 12.29. This will set the CURRENCY field as the currency key for 12
as shown in Figure 12.31.
the PRICE field.
496 497
12 Working with Dates, Times, Quantities, and Currencies 12.5 Updating the Shopping Cart Example
ADD_PRODUCT method to take an additional parameter for quantity and will Next, update the GET_CART method to return the quantity and unit of mea- Updating GET_CART
need to update the GET_CART method to return the quantity and unit of sure. To do this, first update the t_cart definition to include the quantity
measure for all the items in the cart. and unit of measure variables, as shown in bold in Listing 12.25.
Updating First, let’s update the ADD_PRODUCT method. To do this, update the method …
add_product definition to include the IMPORTING parameter ip_quantity as shown in Lis- PUBLIC SECTION.
method
ting 12.23. Add the new parameter as an optional parameter so that other TYPES: BEGIN OF t_cart,
programs aren’t impacted by the change. product TYPE zproduct-product,
description TYPE zproduct_text-description,
…
quantity TYPE zcart-quantity,
add_product IMPORTING ip_product TYPE zproduct-product
uom TYPE zproduct-uom,
ip_quantity TYPE zcart-quantity OPTIONAL,
END OF t_cart,
…
…
Listing 12.23 Updated Definition for ADD_PRODUCT Method
Listing 12.25 Updates to T_CART Definition in ZCL_SHOPPING_CART
Now you can update the ADD_PRODUCT method implementation. The change
Now in the GET_CART method, add the new fields to the SELECT statement, as 12
will be to check if ip_quantity has a value and, if it does, to use that value in
shown in Listing 12.26.
the local structure; otherwise, set the local structure quantity to 1. You can
also now change the INSERT statement to a MODIFY statement. This will allow METHOD get_cart.
the ADD_PRODUCT method to be called to change the quantity and to add new “using new Open SQL
products. This is accomplished using the code in Listing 12.24, which has the SELECT zcart~product, description, quantity, uom
specific changes in bold. FROM zcart
INNER JOIN zproduct
METHOD add_product. ON zcart~product = zproduct~product
DATA: cart TYPE zcart. INNER JOIN zproduct_text
cart-customer = customer. ON zcart~product = zproduct_text~product
cart-product = ip_product. WHERE zproduct_text~language = @sy-langu
IF ip_quantity IS NOT INITIAL. AND zcart~customer = @customer
cart-quantitity = ip_quantity. INTO TABLE @rt_cart.
ELSE.
cart-quantity = 1. “using old Open SQL
ENDIF. SELECT zcart~product description quantity uom
INTO TABLE rt_cart.
MODIFY zcart FROM ls_cart. FROM zcart
ENDMETHOD. INNER JOIN zproduct
ON zcart~product = zproduct~product
Listing 12.24 Updated ADD_PRODUCT Method Implementation
INNER JOIN zproduct_text
ON zcart~product = zproduct_text~product
498 499
12 Working with Dates, Times, Quantities, and Currencies 12.5 Updating the Shopping Cart Example
ENDMETHOD.
12.5.3 Updating the ABAP Programs Figure 12.32 Updated Selection Texts in ZPRODUCT_MAINT
ZPRODUCT_MAINT You’re now ready to update the maintenance ABAP programs. First, let’s
parameters update the ZPRODUCT_MAINT program. In Listing 12.27, we add the additional
parameters needed for price, currency, and unit of measurement, all shown 12
in bold.
…
SELECTION-SCREEN BEGIN OF BLOCK product WITH FRAME TITLE text-001.
PARAMETERS: p_prod TYPE zproduct-product,
p_desc TYPE zproduct_text-description
LOWER CASE,
p_price TYPE zproduct-price,
p_curr TYPE zproduct-currency,
p_uom TYPE zproduct-uom.
SELECTION-SCREEN END OF BLOCK product. Figure 12.33 Updated ZPRODUCT_MAINT Selection Screen
500 501
12 Working with Dates, Times, Quantities, and Currencies 12.5 Updating the Shopping Cart Example
When using inline data declarations, the SELECT statement can be quickly Next, let’s update the ZCART_MAINT program to utilize the new currency and ZCART_MAINT
updated to display the new fields, as shown in Listing 12.29. quantity options. In Listing 12.31, you can see that we added a new parame- changes
ter for the quantity and added it as a parameter when calling the ADD_PROD-
…
UCT method. Notice that we now have to indicate which parameters we’re
SELECT zproduct~product, description, price, currency, uom
passing when calling the ADD_PRODUCT method.
FROM zproduct
INNER JOIN zproduct_text …
ON zproduct~product = zproduct_text~product PARAMETERS: p_cust TYPE zcart-customer OBLIGATORY,
WHERE language = @sy-langu p_prod TYPE zcart-product,
INTO TABLE @DATA(products). p_qty TYPE zcart-quantity.
… …
ELSEIF p_add = abap_true.
Listing 12.29 Updating SELECT Statement with Inline Data Declarations
o_cart->add_product( ip_product = p_prod ip_quantity = p_qty ).
…
When not using inline data declarations, you need to update the type defi-
nition before you can update the SELECT statement, as shown in Listing Listing 12.31 Updates for Program ZCART_MAINT
12.30. 12
Now, press the Activate button to activate these changes and make the new
ELSEIF p_dis = abap_true.
parameter available in the selection texts screen.
TYPES: BEGIN OF t_products,
product TYPE zproduct-product, Navigate to the selection screen texts, as described earlier for the ZPRODUCT_ ZCART_MAINT
description TYPE zproduct_text-description, MAINT program, and check the DDIC Reference checkbox for the new param- selection texts
price TYPE zproduct-price, eter. After activating the changes, the selection screen should look as
currency TYPE zproduct-currency, shown in Figure 12.34.
uom TYPE zproduct-uom,
END OF t_products.
You can now press the Activate button to activate the program. The ZPRO-
DUCT_MAINT ABAP program is now ready to handle currencies and quantities.
502 503
12 Working with Dates, Times, Quantities, and Currencies
The ZCART_MAINT program is now ready to handle quantities. Add data using
both programs to test the new functionality.
12.6 Summary
This chapter covered some important steps and tools for working with
dates, times, and timestamps. With the information covered here, you can
now create ABAP applications that can accurately calculate dates and times
across various time zones and consider working days to calculate import-
ant dates.
We also covered how to work with quantities and currencies in both the
ABAP Dictionary and in ABAP programs and how to read and convert quan-
tities and currencies.
Finally, we updated the shopping cart program from Chapter 10 and Chap-
ter 11 to use quantities and currencies.
In the next chapter, you’ll learn to work with classic dynpro screens.
504
Contents
Preface ............................................................................................................................... 17
3 ABAP 101 51
7
Contents Contents
3.5 Event Blocks ..................................................................................................... 92 4.7 Creating a New Domain ............................................................................. 135
3.5.1 INITIALIZATION ................................................................................ 93 4.8 Creating a New Data Element .................................................................. 139
3.5.2 AT SELECTION-SCREEN .................................................................. 93
4.9 Creating and Editing Tables ...................................................................... 144
3.5.3 START-OF-SELECTION .................................................................... 95
4.9.1 Viewing the Flight Table Configuration .................................. 144
3.6 Formatting Code ............................................................................................ 95 4.9.2 Creating an Append Structure ................................................... 151
3.7 Comments ......................................................................................................... 97 4.9.3 Creating a Custom Transparent Table .................................... 154
3.7.1 Common Commenting Mistakes .............................................. 98 4.10 Documentation ............................................................................................... 161
3.7.2 Using Comments while Programming .................................... 100
4.11 Viewing Data in the Database Tables .................................................. 162
3.8 Debugging Basics ........................................................................................... 100 4.11.1 Data Preview in Eclipse ................................................................. 162
3.8.1 Program to Debug .......................................................................... 101 4.11.2 Data Browser in SAP GUI .............................................................. 164
3.8.2 Breakpoints in Eclipse ................................................................... 103 4.11.3 Setting Up the Flights Example Data ....................................... 169
3.8.3 Breakpoints in the SAP GUI ......................................................... 108
4.12 Table Maintenance Dialogs ....................................................................... 170
3.8.4 Watchpoints in Eclipse ................................................................. 113
4.12.1 Generating Maintenance Dialog for a Table ......................... 170
3.8.5 Watchpoints in SAP GUI ............................................................... 116
4.12.2 Table Maintenance Transaction SM30 ................................... 172
8 9
Contents Contents
4.13 Structures and Table Types ....................................................................... 174 6 Storing Data in Working Memory 229
4.13.1 Creating Structures ........................................................................ 174
4.13.2 Creating Table Types ..................................................................... 176
6.1 Using ABAP Dictionary Data Types ........................................................ 229
4.14 Search Help ....................................................................................................... 177
6.2 Creating Data Types with the TYPE Keyword ................................... 231
4.15 Views ................................................................................................................... 181
6.3 Field Symbols ................................................................................................... 233
4.16 Summary ........................................................................................................... 184
6.4 Defining Internal Tables ............................................................................. 234
6.4.1 Defining Standard Tables ............................................................ 234
6.4.2 Keys in Internal Tables .................................................................. 236
5 Accessing the Database 185 6.4.3 Defining Sorted Tables ................................................................. 238
6.4.4 Defining Hashed Tables ............................................................... 240
5.1 SQL Console in Eclipse ................................................................................. 186 6.5 Reading Data from Internal Tables ........................................................ 241
6.5.1 READ TABLE ....................................................................................... 241
5.2 Reading Data ................................................................................................... 187
6.5.2 LOOP AT ............................................................................................. 247
5.2.1 SELECT Statements ........................................................................ 188
5.2.2 INNER JOIN ........................................................................................ 192 6.6 Modifying Internal Tables ......................................................................... 250
5.2.3 LEFT OUTER JOIN ............................................................................. 197 6.6.1 Inserting/Appending Rows ......................................................... 250
5.2.4 FOR ALL ENTRIES IN ........................................................................ 199 6.6.2 Changing Rows ................................................................................ 253
5.2.5 With SELECT-OPTIONS .................................................................. 201 6.6.3 Deleting Rows .................................................................................. 255
5.2.6 Aggregate Expressions in SELECT Statements ..................... 203 6.7 Other Internal Table Operations ............................................................. 257
5.2.7 New Open SQL ................................................................................. 205 6.7.1 Copying Table Data ........................................................................ 257
5.2.8 ABAP CDS Views .............................................................................. 207 6.7.2 SORT .................................................................................................... 258
5.3 Changing Data ................................................................................................ 210 6.7.3 DELETE ADJACENT DUPLICATES FROM .................................... 260
5.3.1 INSERT ................................................................................................ 210 6.8 Which Table Should Be Used? .................................................................. 261
5.3.2 MODIFY/UPDATE ............................................................................ 211
6.9 Updating ABAP Dictionary Table Type ................................................. 263
5.3.3 DELETE ................................................................................................ 213
6.10 Obsolete Working Memory Syntax ....................................................... 265
5.4 Table Locks ........................................................................................................ 214
6.10.1 WITH HEADER LINE ........................................................................ 266
5.4.1 Viewing Table Locks ....................................................................... 216
6.10.2 OCCURS .............................................................................................. 266
5.4.2 Creating Table Lock Objects ........................................................ 218
6.10.3 Square Brackets ............................................................................... 267
5.4.3 Setting Table Locks ........................................................................ 220
6.10.4 Short Form Table Access .............................................................. 267
5.5 Performance Topics ...................................................................................... 224 6.10.5 BINARY SEARCH ............................................................................... 267
5.6 Obsolete Database Access Keywords ................................................... 226 6.11 Summary ........................................................................................................... 268
5.6.1 SELECT…ENDSELECT ....................................................................... 226
5.6.2 Short Form Open SQL .................................................................... 227
5.7 Summary ........................................................................................................... 227
10 11
Contents Contents
7 Making Programs Modular 269 8.2.2 Creating a Message Class ............................................................ 333
8.2.3 Using the MESSAGE Keyword ..................................................... 336
7.1 Separation of Concerns ............................................................................... 269 8.3 Exception Classes ........................................................................................... 341
8.3.1 Unhandled Exceptions .................................................................. 342
7.2 Subroutines ...................................................................................................... 272
8.3.2 TRY/CATCH Statements ............................................................... 348
7.3 Introduction to Object-Oriented Programming .............................. 274 8.3.3 Custom Exception Classes ........................................................... 350
7.3.1 What Is an Object? ......................................................................... 274
8.4 Non-Class-Based Exceptions ..................................................................... 355
7.3.2 Modularizing with Object-Oriented Programming ............ 276
8.5 Summary ........................................................................................................... 358
7.4 Structuring Classes ........................................................................................ 277
7.4.1 Implementation versus Definition ........................................... 278
7.4.2 Creating Objects ............................................................................. 278
7.4.3 Public and Private Sections ......................................................... 280 9 Presenting Data Using the
7.4.4 Class Methods ................................................................................. 282
ABAP List Viewer 361
7.4.5 Importing, Returning, Exporting, and Changing .................. 286
7.4.6 Constructors ..................................................................................... 293
9.1 What Is ALV? .................................................................................................... 361
7.4.7 Recursion ........................................................................................... 295
7.4.8 Inheritance ........................................................................................ 297 9.2 Report Example Using an SALV Table ................................................... 366
7.4.9 Composition ..................................................................................... 302 9.3 Report Example Using SALV Tree ........................................................... 371
7.5 Global Classes .................................................................................................. 308 9.4 ALV with Integrated Data Access ........................................................... 380
7.5.1 How to Create Global Classes in Eclipse ................................. 309
9.5 Outdated ALV Frameworks ....................................................................... 383
7.5.2 How to Create Global Classes in Transaction SE80 ............ 310
9.5.1 REUSE_ALV_GRID_DISPLAY Function Module ...................... 383
7.5.3 Using the Form-Based View in Transaction SE80 ................ 312
9.5.2 CL_GUI_ALV_GRID Class .............................................................. 385
7.6 Design Patterns .............................................................................................. 317
9.6 Summary ........................................................................................................... 386
7.7 Function Modules .......................................................................................... 317
7.7.1 Creating Function Groups and Modules in Eclipse ............. 318
7.7.2 Creating Function Groups in Transaction SE80 ................... 322
7.7.3 Calling Function Modules ............................................................ 326 10 Creating a Shopping Cart Example 387
12 13
Contents Contents
10.3 Accessing the Database Solution ........................................................... 405 12.1.3 Datum Date Type ............................................................................ 473
12.1.4 System Date Fields ......................................................................... 475
10.4 Creating a Message Class for the Solution ......................................... 415
12.1.5 Date-Limited Records .................................................................... 475
10.5 Creating Classic Screens for the Solution ........................................... 416
12.2 Times ................................................................................................................... 477
10.5.1 Product Maintenance Program ................................................. 417
12.2.1 Calculating Time ............................................................................. 477
10.5.2 Shopping Cart Maintenance Program ..................................... 423
12.2.2 Timestamps ...................................................................................... 478
10.6 Summary ........................................................................................................... 429 12.2.3 SY-UZEIT (System Time versus Local Time) ............................ 482
12.3 Quantities ......................................................................................................... 482
12.3.1 Quantity Fields in Data Dictionary ........................................... 484
11 Working with Strings and Texts 431 12.3.2 Converting Quantities .................................................................. 485
12.4 Currencies .......................................................................................................... 486
11.1 String Manipulation ..................................................................................... 431 12.4.1 Currency Fields in Data Dictionary ........................................... 487
11.1.1 String Templates ............................................................................ 432 12.4.2 Converting Currencies .................................................................. 488
11.1.2 String Functions .............................................................................. 435
12.5 Updating the Shopping Cart Example .................................................. 490
11.2 Text Symbols ................................................................................................... 437 12.5.1 Updating the Database ................................................................ 491
11.2.1 Creating Text Symbols .................................................................. 437 12.5.2 Updating the Global Class ........................................................... 497
11.2.2 Translating Text Symbols ............................................................ 442 12.5.3 Updating the ABAP Programs .................................................... 500
11.3 Translating Data in Tables ......................................................................... 445 12.6 Summary ........................................................................................................... 504
11.4 Translating Messages .................................................................................. 451
11.6 Updating the Shopping Cart Example ................................................. 454 13 User Interface Technologies 505
11.6.1 Updating the Database ................................................................ 454
11.6.2 Using the Text Table ...................................................................... 460 13.1 Working with Classic Dynpro Screens .................................................. 505
13.1.1 Dynpro Screen Events ................................................................... 506
11.7 Summary ........................................................................................................... 463
13.1.2 Creating a Dynpro Screen ............................................................ 508
13.2 Modern UI Technologies ............................................................................. 528
13.2.1 Web Dynpro ...................................................................................... 529
12 Working with Dates, Times, Quantities, 13.2.2 SAP Screen Personas ...................................................................... 531
and Currencies 465 13.2.3 SAP Gateway, SAPUI5, and SAP Fiori ........................................ 532
13.3 Summary ........................................................................................................... 534
12.1 Dates ................................................................................................................... 465
12.1.1 Date Type Basics ............................................................................. 466
12.1.2 Factory Calendars ........................................................................... 469
14 15
Contents
14.10 Backward Compatibility and Dealing with Legacy Code ............. 621
Appendices 525
16
Index
673
Index Index
674 675
Index Index
Deletion anomaly ...................................... 124 Enhancement category ................. 153, 160 File IF .......................................................................... 72
Delivery and maintenance .................... 146 Enhancement framework ............ 659, 662 interfaces ................................................. 645 AND ............................................................... 73
DEQUEUE ................................... 216, 220, 223 Enhancements ............................................ 654 logical name ........................................... 582 ELSE ............................................................... 73
Design patterns .......................................... 317 ENQUEUE ...................................................... 220 on application server .......................... 577 ELSEIF ........................................................... 75
DEV environment ..................................... 536 Enterprise resource planning ................. 23 on presentation server ....................... 567 OR ................................................................... 73
Development guidelines ........................ 582 Entity .............................................................. 123 transfer protocol ................................... 645 IF statement operators ............................... 76
Development standards ........................... 42 Entity relationship diagrams Flight model INCLUDE ........................................................ 517
DevOps ........................................................... 535 (ERDs) ......................................................... 123 load data .................................................. 169 Initial value .................................... 51, 71, 147
DIV ..................................................................... 66 Entry help/check ........................................ 159 Floor .................................................................. 69 INITIALIZATION ............................................ 92
DIVIDE .............................................................. 68 ERD ..................................... 123, 389, 455, 490 Flow control ................................................... 72 Inline data declaration ... 61, 189, 420, 427
DO ...................................................................... 79 crow’s foot notation, relationship Flow logic ...................................................... 516 INNER JOIN .......................................... 192, 414
Documentation ................................ 161, 586 indication ............................................ 126 FLUSH_ENQUEUE ..................................... 222 Input help ..................................................... 178
Domain .................... 121, 130, 135, 394, 400 normalized ............................................... 125 FOR ALL ENTRIES IN ................................. 199 INSERT ......................................... 210, 250, 263
range .......................................................... 137 Event ................................................................. 92 Foreign key ............................... 126, 148, 399 hashed table ........................................... 252
DSAG guidelines ........................................ 584 AT SELECTION SCREEN .......................... 93 cardinality ............................................... 157 INDEX ........................................................ 250
Dynamic breakpoints .............................. 106 INITIALIZATION ....................................... 93 create ......................................................... 157 LINES FROM ............................................ 251
Dynamic program ..................................... 505 START-OF-SELECTION ........................... 95 set ............................................................... 156 sorted table ............................................. 252
Dynpro ........................................................... 505 Exception ...................................................... 341 Form ............................................................... 649 Insert anomaly ........................................... 125
create screen ........................................... 508 500 SAP internal server error ........... 343 FORM CHANGING ..................................... 274 Integrated development
Screen events .......................................... 506 CATCH BEFORE UNWIND ................... 350 FORM...ENDFORM ..................................... 272 environments (IDEs) ........................... 627
screen flow diagram ............................ 507 CATCH...INTO .......................................... 349 Format your code ......................................... 96 Internal tables ............................. 59, 229, 261
categories ................................................. 350 frac ..................................................................... 69 hashed key ............................................... 237
E custom exception classes ................... 350 Fully buffered ............................................. 225 hashed table .................................. 240, 261
function modules .................................. 356 Function group ....................... 170, 318, 322 key ............................................................... 236
Eclipse non-class based exceptions ............... 355 Function modules ............................ 318, 324 secondary keys ....................................... 237
ABAP perspective .................................... 36 RAISE EXCEPTION TYPE ...................... 349 CALL FUNCTION .................................... 326 SORT ........................................................... 258
ABAP projects ......................................... 636 resumable exceptions ......................... 349 parameters .............................................. 321 sorted key ................................................. 237
create program ........................................ 35 RESUME ..................................................... 350 sorted table .................................... 239, 261
create project ............................................ 39 short dump .............................................. 342 G standard key ........................................... 237
dynpro ....................................................... 509 ST22 ............................................................. 344 standard table ............................... 234, 261
format code ............................................... 96 TRY…CATCH ............................................. 348 Generic area buffered .............................. 225 INTO ................................................................ 206
open project .............................................. 38 unhandled ................................................ 342 GETWA_NOT_ASSIGNED ....................... 233 INTO TABLE .................................................. 206
outline ......................................................... 38 Exclusive lock .............................................. 215 Global class .................................................. 389 ipow ......................................................... 69, 102
perspectives ............................................. 634 Execute program ........................................ 610 Global variables ......................................... 272 ITAB_ILLEGAL_SORT_ORDER .............. 240
problems ..................................................... 38 Execution stack ........................................... 105
project explorer ....................................... 38 EXIT .................................................................... 79 H J
SQL Console ................................... 186, 188 Extended Program Check ............. 611, 612
versus Transaction SE80 ...................... 38 Hash board .......................................... 240, 263 JavaScript ......................................................... 34
views ............................................................ 36 F High-level documentation .................... 586
workspaces .............................................. 633 HTML5 .............................................................. 34 K
Electronic Data Interchange (EDI) ....... 647 f ........................................................................... 53
ELSE ................................................................... 73 Field I Key ................................................................... 147
END OF ............................................................. 58 catalog ....................................................... 384 Key fields/candidate ................................ 157
ENDDO ............................................................. 79 label ............................................................ 141 Identifying relationship ......................... 126 Keyword
ENDIF ................................................................ 72 Field symbols ............................................... 233 IDES solution .............................................. 627 APPEND .................................................... 251
ASSIGN ....................................................... 233 IDocs ............................................................... 647 AS ................................................................ 194
676 677
Index Index
678 679
Index Index
680 681
Index Index
String .................................................. 45, 56, 61 T Transaction SE80 (Cont.) SUIM (User Information System) ... 564
ALIGN ........................................................ 433 create screen ........................................... 509 VOFM ......................................................... 657
chaining strings ..................................... 433 Table edit program ............................................. 44 Translate ....................................................... 454
concat_lines_of ..................................... 435 custom transparent ............................. 154 format code ............................................... 96 Transparent table ........ 121, 123, 144, 154,
CONDENSE ............................................... 435 normalized ............................................... 134 form-based view ................................... 312 210, 235, 236, 388, 389
DECIMALS ................................................ 435 SBOOK ....................................................... 134 IDE settings ................................................ 44 currency/quantity
PAD ............................................................. 433 SCARR ........................................................ 134 pretty print ................................................. 96 fields ................................... 484, 487, 488
SIGN ............................................................ 434 SCUSTOM ................................................. 134 program attributes ................................. 41 Transport ...................................................... 538
string functions ..................................... 435 SFLIGHT .................................................... 134 source code view ................................... 312 view ............................................................ 548
string literals ................................. 432, 438 SPFLI ........................................................... 134 Transactions ................................................... 29 Transport management .......................... 539
string template ...................................... 432 technical settings .................................. 149 ABAPDOCU ...................................... 55, 583 Transport organizer ................................. 546
strlen .......................................................... 435 text table .................................................. 445 AL11 ............................................................. 577 Transport request ...................................... 542
substring ......................................... 436, 466 view single row ....................................... 189 CMOD ........................................................ 655 Transport route .......................................... 539
substring_before ................................... 436 Table configuration .................................. 144 CUNI ........................................................... 483 trunc .................................................................. 69
substring_from ...................................... 436 Table locks .................................................... 214 FILE ............................................................. 582 TYPE .................................... 51, 57, 74, 97, 231
substring_to ............................................ 436 create ......................................................... 218 OB08 .......................................................... 487
timestamp formatting ........................ 480 deadlock .................................................... 214 OY03 .......................................................... 486 U
WIDTH ....................................................... 433 mode .......................................................... 217 SAT ............................................................. 617
Structure .................................... 174, 210, 235 parameter ................................................ 217 SCC4 ........................................................... 538 UBTRACT .......................................................... 68
Subpackages ................................................ 540 set ................................................................ 220 SE10 ............................................................ 546 UML ................................................................. 408
Subroutines ................................................. 272 view ............................................................. 216 SE11 ... 122, 128, 129, 135, 139, 142, 144, Units of measurement ............................ 483
PERFORM ................................................. 272 Table type ......................... 174, 189, 232, 263 154, 170, 174, 176, 216, 218, 264, 393, UPDATE ......................................................... 212
Switch Framework ..................................... 662 Tables .............................................................. 227 395, 397, 400, 401, 455, 484, 487, 491 Update anomaly ........................................ 124
sy-batch ........................................................... 64 client-dependent .................................... 537 SE16N ......................................................... 167 User interface (UI) .............................. 80, 505
sy-datlo ............................................................ 64 client-independent ................................ 537 SE38 ............................................................ 169 USING ............................................................. 273
sy-datum ......................................................... 64 Technical settings ......... 150, 160, 400, 404 SE63 ......................................... 446, 459, 589
sy-index ........................................................... 64 Template SE71 ............................................................. 652 V
SYST ................................................................... 63 ABAP Editor ............................................. 596 SE80 .................................................... 40, 408
System fields .......................................... 47, 63 Text editor .................................................... 523 SE91 ................................................... 331, 333 VALUE ........................................................ 51, 71
editing ......................................................... 64 Text formats ................................................ 567 SEGW ......................................................... 649 Value range .................................................. 137
sy-batch ...................................................... 64 Text symbols ............................ 419, 424, 437 SM30 ................................................. 170, 172 Variable
sy-datlo ....................................................... 64 comparison .............................................. 439 SM36 .......................................................... 603 assign value to .......................................... 65
sy-datum ............................................. 63, 64 translation ............................................... 442 SM37 ........................................................... 606 chain together ........................................... 52
sy-index ....................................................... 64 Third normal form .................................... 125 SM59 .......................................................... 647 Variable naming ........................................... 52
sy-subrc ....................................................... 64 table ............................................................ 125 SM62 .......................................................... 609 Variables .......................................................... 51
sy-tabix ....................................................... 64 Transaction SE11 SMDAEMON ........................................... 665
sy-timlo ....................................................... 64 ABAP Dictionary .................................... 123 SMOD ........................................................ 655 W
sy-uzeit ........................................................ 64 Transaction SE63 SOAMANAGER ....................................... 648
sy-subrc ............................... 64, 246, 329, 357 translation editor .................................. 448 SP01 ............................................................ 609 Watchpoints ....................................... 101, 113
sy-tabix ......................................... 64, 246, 249 Transaction SE80 ST01 ............................................................ 563 Web Dynpro ABAP .................................... 529
sy-timlo ........................................................... 64 ABAP Workbench .................................... 40 ST22 ................................................... 344, 350 Web Services ................................................ 648
sy-uzeit ............................................................ 64 create new program ............................... 40 STMS .......................................................... 539 WHERE ........................................ 191, 198, 199
create program ........................................ 40 SU01 ........................................................... 551 WHERE IS NULL .......................................... 198
SU21 ............................................................ 551 WHERE..IN .................................................... 201
SU3 .............................................................. 474 WHILE loops ................................................... 79
682 683
Index
Whitespace ..................................................... 66 Z
Wireframe .................................. 391, 417, 423
WRITE ............................................................... 45 Zero-to-many relationship .................... 127
WRITE Hello, World! program ................ 45 Zero-to-one relationship ......................... 127
X
xUnit ............................................................... 593
684
First-hand knowledge.