TAW12 1/3 - hservers.org

420
© SAP AG TAW12 0-1 SAP AG 2003 TAW12 ABAP Workbench Concepts (1/3) SAP AG TAW12 1/3 TAW12 1/3 ABAP Workbench Concepts ABAP Workbench Concepts n R/3 System n Release 4.6D or above n 2003/Q2 n Material number 5006 1051

Transcript of TAW12 1/3 - hservers.org

© SAP AG TAW12 0-1

SAP AG 2003

TAW12 ABAP Workbench Concepts (1/3)

SAP AG

TAW12 1/3 TAW12 1/3 ABAP Workbench ConceptsABAP Workbench Concepts

n R/3 System n Release 4.6D or above n 2003/Q2 n Material number 5006 1051

© SAP AG TAW12 0-2

SAP AG 2003

Copyright 2003 SAP AG. All rights reserved.

No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG. The information contained herein may be changed without prior notice.

All rights reserved.

Copyright

Comments on trademarks: n Some software products marketed by SAP AG and its distributors contain proprietary software

components of other software vendors. n Microsoft®, WINDOWS®, NT®, EXCEL®, Word®, PowerPoint® and SQL Server® are registered

trademarks of Microsoft Corporation. n IBM®, DB2®, DB2 Universal Database, OS/2®, Parallel Sysplex®, MVS/ESA, AIX®, S/390®,

AS/400®, OS/390®, OS/400®, iSeries, pSeries, xSeries, zSeries, z/OS, AFP, Intelligent Miner, WebSphere®, Netfinity®, Tivoli®, Informix and Informix® Dynamic ServerTM are trademarks of IBM Corporation in USA and/or other countries.

n ORACLE® is a registered trademark of ORACLE Corporation. n UNIX®, X/Open®, OSF/1® and Motif® are registered trademarks of the Open Group. n Citrix®, the Citrix logo, ICA®, Program Neighborhood®, MetaFrame®, WinFrame®,

VideoFrame®, MultiWin® and other Citrix product names referenced herein are trademarks of Citrix Systems, Inc.

n HTML, DHTML, XML, XHTML are trademarks or registered trademarks of W3C®, World Wide Web Consortium, Massachusetts Institute of Technology.

n JAVA® is a registered trademark of Sun Microsystems, Inc. n JAVASCRIPT® is a registered trademark of Sun Microsystems, Inc., used under license for

technology invented and implemented by Netscape. n MarketSet and Enterprise Buyer are jointly owned trademarks of SAP AG and Commerce One. n SAP, R/, mySAP, mySAP.com, xApps, xApp, and other SAP products and services mentioned

herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany and in several other countries all over the world. All other product and service names mentioned are the trademarks of their respective companies.

© SAP AG TAW12 0-3

SAP AG 2003

Development Consultant mySAP Technology –ABAP Workbench

mySAP Technology- ABAP Workbench Concepts

TAW12 15 days Development consultantcertification –mySAP Technology – ABAP Workbench

TAW10 10 days

mySAP Technology -ABAP Workbench Fundamentals

© SAP AG TAW12 0-4

SAP AG 2003

Course Prerequisites

Required

l TAW10: mySAP Technology - ABAP Workbench Fundamentalsor comparable knowledge

© SAP AG TAW12 0-5

SAP AG 2003

Target Group

??

Target group

l Development consultants and developers who are responsible for adjusting and developing business applications in ABAP/ABAP objects

Duration

l 15 days

© SAP AG TAW12 0-6

SAP AG 2003

At the end of this training course you will be able to:

l Describe the concepts of the ABAP programming language

l Use the ABAP programming language and the ABAP Workbench tools to develop your own business applications or to make individual adjustments to SAP standard software

l Directly use your knowledge as a junior consultant in an initial practical phase

Goals

© SAP AG TAW12 0-7

SAP AG 2003

Complex mySAP.com technologies

Complex ABAP Workbench Fundamentals

Complex ABAP Objects

Case study

Course Content: mySAP Technology –ABAP Workbench Fundamentals

Preface

n This SAP Consultant Education training course contains different individual courses (sections), each of which handles a separate topic.

n Each individual course (section) is divided into different units.

© SAP AG TAW12 0-8

SAP AG 2003

Complex Programming Database Updates

Complex Solution Manager

Complex Enhancements and Modifications

Case study

Complex ABAP Dictionary

Complex Techniques of List Processing

Complex Programming User Dialogs

Course Content: mySAP Technology –ABAP Workbench Concepts

Preface

n This SAP Consultant Education training course contains different individual courses (sections), each of which handles a separate topic.

n Each individual course (section) is divided into different units.

© SAP AG TAW12 1-1

SAP AG 2003

Complex: ABAP Dictionary

© SAP AG TAW12 1-2

SAP AG 2003

Course Content: ABAP Dictionary

Unit Introduction

Unit Tables in the ABAP Dictionary

Unit Performance in Table Accesses

Unit Consistency through Input Checks

Unit Dependencies of ABAP Dictionary Objects

Unit Table Updates

Unit Views

Unit Search Help

Appendix

© SAP AG TAW12 2-1

SAP AG 1999

l Function of the ABAP Dictionary in the R/3 System

l Definition of database objects

l User-defined types

l Services in the ABAP Dictionary

l Linking to the development and runtime environments

Introduction

© SAP AG TAW12 2-2

SAP AG 2002

Course Objectives

At the end of this unit, you will be able to:

l Define the function of the ABAP Dictionary in the R/3 System

l Describe the ways to define data objects and types

l Describe the services provided by the ABAP Dictionary

l Explain how the ABAP Dictionary is linked to the development and runtime environments

© SAP AG TAW12 2-3

SAP AG 2002

Function of the ABAP Dictionary

DB table

Services

ScreenPoss. values

Type definitions

Structure

Table typeData elements

F4

DB objects

Table

n The ABAP Dictionary permits central management of all the data definitions used in the R/3 System. n In the ABAP Dictionary, you can create user-defined types (data elements, structures, and table

types) for use in ABAP programs or in interfaces of function modules. Database objects such as tables and database views can also be defined in the ABAP Dictionary and created with this definition in the database.

n The ABAP Dictionary also provides a number of services that support program development. For example, setting and releasing locks, defining an input help (F4 help), and attaching a field help (F1 help) to a screen field are supported.

© SAP AG TAW12 2-4

SAP AG 1999

Database

Database Objects in the ABAP Dictionary

Table 1

ABAP Dictionary

Table 2

View

Objects are automatically created in the DB and adjusted to changes

n Tables and database views can be defined in the ABAP Dictionary. n These objects are created in the underlying database with this definition. Changes in the definition of

a table or database view are also automatically made in the database. n Indexes can be defined in the ABAP Dictionary to speed up access to data in a table. These indexes

are also created in the database.

© SAP AG TAW12 2-5

SAP AG 2002

Type Definitions in the ABAP Dictionary

ZIP Town name Street House no.

Numbers

Employee

Name Address Telephone

First name Last name Town Address

n Three different type categories exist in the ABAP Dictionary: � Data elements: Describe an elementary type by defining the data type, length, and possibly

decimal places. � Structures: Consist of components that can have any type. � Table types: Describe the structure of an internal table.

n Any complex user-defined type can be built from these basic types. n Example: The data of an employee is stored in a structure EMPLOYEE with the component’s

NAME, ADDRESS and TELEPHONE. Component NAME is also a structure with component’s FIRST NAME and LAST NAME. Both of these components are elementary, for example, their type is defined by a data element. The type of component ADDRESS is also defined by a structure whose components are also structures. A table type is used to define component TELEPHONE (because an employee can have more than one telephone number).

n Types are used for example in ABAP programs or to define the types of interface parameters of function modules.

© SAP AG TAW12 2-6

SAP AG 2002

Services of the ABAP Dictionary

Carrier

Flight number

. . .

Maintenance of flights

LH

No.

Depart. city Arrival city

Carrier

0400 Frankfurt New York

0402 Frankfurt New York

LH

2402 Frankfurt Berlin

... ... ...

Code of the flight connection

Code defining a flight connection between two cities, e.g. 0400 Frankfurt - New York.

F1

F4

n The ABAP Dictionary supports program development with a number of services: � Input helps (F4 helps) for screen fields can be defined with search helps. � Field help (F1 help) can be easily assigned to screen fields by creating documentation for the data

element. � An input check that ensures that the values entered are consistent can easily be defined for screen

fields using foreign keys. � The ABAP Dictionary provides support when you set and release locks. To do so, you must create

lock objects in the ABAP Dictionary. Function modules for setting and releasing locks are automatically generated from these lock objects; these can then be linked into the application program. � The performance when accessing this data can be improved for database objects (tables, views)

with buffering settings. � By logging, you can switch on the automatic recording of changes to the table entries.

© SAP AG TAW12 2-7

SAP AG 1999

Linking to the Development and Runtime Environment

ABAP DictionaryRead type

definitions

Reads structure of database objects

Runtime environment

Development environment

ABAPInterpreter

ScreenInterpreter

ABAPtools

ScreenPainter Database

interface

n The ABAP Dictionary is actively integrated in the development and runtime environments. Each change takes immediate effect in the relevant ABAP programs and screens.

n Examples: � When a program or screen is generated, the ABAP interpreter and the screen interpreter access the

type definitions stored in the ABAP Dictionary. � The ABAP tools and the Screen Painter use the information stored in the ABAP Dictionary to

support you during program development. An example of this is the Get from Dictionary function in the Screen Painter, with which you can place fields of a table or structure defined in the ABAP Dictionary in a screen. � The database interface uses the information about tables or database views stored in the ABAP

Dictionary to access the data of these objects.

© SAP AG TAW12 2-8

SAP AG 2002

Unit Summary

l The ABAP Dictionary manages data definitions.

l User-defined types can be created in the ABAP Dictionary.They can be used, for example, in ABAP programs.

l Tables and database views are defined in the ABAP Dictionary and automatically created with this definition in the underlying database.

l The ABAP Dictionary provides a number of services that support program development.

l The ABAP Dictionary is actively integrated in the development and runtime environments.

© SAP AG TAW12 3-1

SAP AG 1999

l Two-level domain concept

l Mapped in the relational database system

l Include structures

l Technical settings

n Data class

n Size category

n Buffering

n Logging

Tables in the ABAP Dictionary

© SAP AG TAW12 3-2

SAP AG 2002

At the end of this unit, you will be able to:

l Create Tables

l Use the two-level domain concept

l Define the technical settings of a table

l Create and use include structures

Course Objectives

© SAP AG TAW12 3-3

SAP AG 2002

Tables and Fields

Key Function fields

Row

Table

Key 1

.

.

.

Key 2

.

.

.

Key n

.

.

.

F 1

.

.

.

F 2

.

.

.

F n

.

.

.

n The structure of the objects of application development are mapped in tables on the underlying relational database.

n The attributes of these objects correspond to fields of the table. n A table consists of columns (fields) and rows (entries). It has a name and different attributes, such as

delivery class and maintenance authorization. n A field has a unique name and attributes; for example, it can be a key field. n A table has one or more key fields, called the primary key. n The values of these key fields uniquely identify a table entry. n You must specify a reference table for fields containing a currency (data type CURR) or quantity

(data type QUAN). It must contain a field (reference field) with the format for currency keys (data type CUKY) or the format for units (data type UNIT). The field is only assigned to the reference field at program runtime.

© SAP AG TAW12 3-4

SAP AG 2002

Basic Objects of the ABAP Dictionary

uses

uses

Table

Tablefield

Data elementData element

DomainDomain

n The basic objects for defining data in the ABAP Dictionary are tables, data elements and domains. The domain is used for the technical definition of a table field (for example, field type and length) and the data element is used for the semantic definition (for example short description).

n A domain describes the value range of a field by its data type and length. The value range can be limited by specifying fixed values.

n A data element describes the meaning of a domain in a certain business context. The data element contains primarily the field help (F1 documentation) and the field labels in the screen.

n A field is not an independent object, but it is table-dependent. The field can only be maintained within a table.

n You can enter the data type and number of places directly for a field. No data element is required in this case. Instead, the data type and number of places is defined by specifying a direct type.

n The data type attributes of a data element can also be defined by specifying a built-in type, where the data type and number of places is entered directly.

© SAP AG TAW12 3-5

SAP AG 2002

Two-Level Domain Concept: Example

Table SPFLI

MANDT

Data element S_FROMAIRPData element S_FROMAIRP Data element S_TOAIRPData element S_TOAIRP

Domain S_AIRPIDDomain S_AIRPID

CARRID ... AIRPFROMCONNID ... AIRPTO

n The flight schedule is stored in table SPFLI. Table fields AIRPFROM (departure airport) and AIRPTO (arrival airport) have the same domain S_AIRPID. Both fields use the same domain because both fields contain airport IDs and therefore have the same technical attributes. They have a different semantic meaning, however, and use different data elements to document this. Field AIRPFROM uses data element S_FROMAIRP and field AIRPTO uses data element S_TOAIRP.

© SAP AG TAW12 3-6

SAP AG 2002

Transparent Tables and Structures

Table

Field 1 Field 2Field 3 Field 4

Structure

Field 1 Field 2 Field 3 Field 4

ABAP Dictionary

Physical definition of the table

TableField 1 Field 2 Field 3 Field 4

Database

n A transparent table is automatically created on the database when it is activated in the ABAP Dictionary. At this time, the database-independent description of the table in the ABAP Dictionary is translated into the language of the database system used.

n The database table has the same name as the table in the ABAP Dictionary. The fields also have the same name in both the database and the ABAP Dictionary. The data types in the ABAP Dictionary are converted to the corresponding data types of the database system.

n The order of the fields in the ABAP Dictionary can differ from the order of the fields on the database. This permits you to insert new fields without having to convert the table. When you add a new field, adjust the order of the fields by changing the database catalog (ALTER TABLE). The new field is added to the database table.

n ABAP programs can access a transparent table in two ways. One way is to access the data contained in the table with OPEN SQL (or EXEC SQL). With the other method, the table defines a structured type that is accessed when variables (or more complex types) are defined.

n You can also create a structured type in the ABAP Dictionary for which there is no corresponding object in the database. Such types are called structures. Structures can also be used to define the types of variables.

© SAP AG TAW12 3-7

SAP AG 1999

Include Structures

Table 2Table 1

Field 1 Field 2 Field A Field B Field 4Field 3 Field A Field B

Field A Field B

Database

Field 1 Field 2 Field A Field BField A Field B Field 3 Field 4

Include structure

n Structures can be included in tables or other structures to avoid redundant structure definitions. n A table may only be included as an entire table. n A chain of includes may only contain one database table. The table in which you are including

belongs to the include chain. This means that you may not include a transparent table in a transparent table.

n Includes may contain further includes. n Foreign key definitions are generally imparted from the include to the including table. The attributes

of the foreign key definition are passed from the include to the including table so that the foreign key depends on the definition in the include.

© SAP AG TAW12 3-8

SAP AG 1999

Technical Settings

Buffering

Table buffer

R/3

In which physical area of the databaseshould the tablebe stored?

Logging

Should the records of the table be

buffered? Should changes to the data records be logged?

How many records will the table probably contain?

Size category

Data class

Data base

Data base

n You must maintain the technical settings when you define a transparent table in the ABAP Dictionary.

n The technical settings are used to individually optimize the storage requirements and accessing behavior of database tables.

n The technical settings can be used to define how the table should be handled when it is created on the database, whether the table should be buffered and whether changes to entries should be logged.

n The table is automatically created on the database when it is activated in the ABAP Dictionary. The storage area to be selected (tablespace) and space allocation settings are determined from the settings for the data class and size category.

n The settings for buffering define whether and how the table should be buffered. n You can define whether changes to the table entries should be logged.

© SAP AG TAW12 3-9

SAP AG 2002

Data Class

Tables in the ABAP Dictionary

TablespaceOrg. data

TablespaceMaster data

TablespaceTrans. data

TablespaceSystem data

Database

Organizational data Transaction data System dataMaster data

Table 1

Table 3

Table 4

Table 2

Table 6

Table 5

Table 9

Table 7

Table 8

Table 1

Table 3

Table 4

Table 2

Table 6

Table 5

Table 9

Table 7

Table 8

n The data class logically defines the physical area of the database (for ORACLE the tablespace) in which your table should be stored. If you choose the data class correctly, the table will automatically be created in the appropriate area on the database when it is activated in the ABAP Dictionary.

n The most important data classes are master data, transaction data, organizational data and system data.

n Master data is data that is rarely modified. An example of master data is the data of an address file, for example, the name, address and telephone number.

n Transaction data is data that is frequently modified. An example is the material stock of a warehouse, which can change after each purchase order.

n Organizational data is data that is defined during customizing when the system is installed and that is rarely modified thereafter. The country keys are an example.

n System data is data that the R/3 System itself needs. The program sources are an example. n Further data classes, called customer data classes (USER, USER1), are provided for customers.

These should be used for customer developments. Special storage areas must be allocated in the database.

© SAP AG TAW12 3-10

SAP AG 2002

Size Category

InitialExtent

FirstExtent

SecondExtent

Technical Settings

Size category

TABA

TABB

TABC

1

3

4

TABATABA

TABBTABB

TABCTABC

Database

n The size category describes the expected storage requirements for the table on the database. n An initial extent is reserved when a table is created on the database. The size of the initial extent is

identical for all size categories. If the table needs more space for data at a later time, extents are added. These additional extents have a fixed size that is determined by the size category specified in the ABAP Dictionary.

n You can choose a size category from 0 to 4. A fixed extent size, which depends on the database system used, is assigned to each category.

n Correctly assigning a size category ensures that you do not create a large number of small extents. It also prevents storage space from being wasted when creating extents that are too large.

© SAP AG TAW12 3-11

SAP AG 2002

Logging

Applicationtransaction

Change a record

System profiles

rec/client =ALL

...

...

TAB

Field 2 Field 3 Field 5

TAB Log tableField 1 Field 2 Field 3

Database

ABAP Dictionary

Log TABLog TAB

n You can use logging to record and store modifications to the entries of a table. n To activate logging, the corresponding field must be selected in the technical settings. Logging,

however, only takes place if the R/3 System was started with a profile containing parameter rec/client. Only selecting the flag in the ABAP Dictionary is not sufficient to trigger logging.

n Parameter rec/client can have the following settings: rec/client = ALL All clients should be logged. rec/client = 000[...] Only the specified clients should be logged. rec/client = OFFLogging is not enabled on this system.

n The data modifications are logged independently of the update. You can display the logs with the Transaction Table History (SCU3).

n Logging creates a bottleneck in the system: � Additional write access for each modification to tables being logged. � This can result in lock situations although the users are accessing different application tables!

© SAP AG TAW12 3-12

SAP AG 2002

Unit Summary

l All the business-oriented data is administered in the form of tables whose definition is stored in the ABAP Dictionary.

l A two-level domain concept is used for defining the tables. The semantic definition is implemented with data elements and the technical definition with domains.

l The fields of include structures can be included in tables.

l The technical settings of a table define how the table should be stored in the database (tablespace, extent size) and whether changes to the data records should be logged.

© SAP AG TAW12 3-13

Exercise Data Explanation of the Symbols in the Exercises and Solutions

Exercises

Solutions

Course Objectives

Business Scenario

Tips & Tricks

Warning or Caution

Data in the Exercises

Type of data Data in the training system

Data model BC_TRAVEL yes

All objects in development class BC_DATAMODEL

yes

All objects in development class BC430 yes

When creating ABAP Dictionary objects in this course, you should adhere to the following conventions:

• Your object names for tables, data elements and domains should begin with Z and end with your two-digit group number (xx).

• Use both your own data elements or domains (Z<Objectname>xx) and standard SAP objects for the table fields.

• All objects should be created as local objects (development class $tmp).

The appendix contains information about the flight data model used in the training courses.

© SAP AG TAW12 3-14

Tables in the ABAP Dictionary Exercises

Unit: Tables in the ABAP Dictionary

At the conclusion of these exercises, you will be able to:

Create tables and use the two-level domain concept

Define the technical settings sensibly

Document fields

Create and use include structures

In these exercises, the tables of the flight model will be enhanced with employee management. This employee management enables the airlines to enter and evaluate data about their employees (for example name, personnel number, salary, department, etc.) and about assignments within the organization (airline departments).

In this exercise, two tables will be created for the employee data and the airline departments.

These tables will be enhanced step-by-step in the following exercises.

1-1 Create two transparent tables ZEMPLOY## and ZDEPMENT## and define their key fields. Define the technical settings when you activate the tables.

Note the following:

Data is maintained for three airlines. An airline has 20,000 employees and between 10 and 30 departments. Do not buffer or log the data. Buffering will be discussed in the exercises for the next unit.

© SAP AG TAW12 3-15

2-1-1 Create table ZEMPLOY##. The data for the employees is maintained here. The names and addresses of the employees and their salaries are stored here.

Table ZEMPLOY##

Field name Data element Domain Type, Length

Client S_MANDT MANDT

Carrier S_CARR_ID S_CARR_ID

Personnel number own own NUMC, 10

First name S_FNAME S_FNAME

Last name S_LNAME S_LNAME

Department code own own CHAR, 4

Area own own CHAR, 1

Salary own own CURR, 10

2 decimal places

Currency S_CURRCODE S_CURR

2-1-2 Create table ZDEPMENT##. This table contains the departments of the airline. Each department can be reached with a telephone and fax number.

Table ZDEPMENT##

Field name Data element Domain Type, Length

Client S_MANDT MANDT

Carrier S_CARR_ID S_CARR_ID

Department code own own CHAR, 4

Telephone own S_PHONE CHAR, 30

Fax own S_PHONE CHAR, 30

2-2 Document fields Personnel number and Department code.

2-3 Changes to tables ZEMPLOY## and ZDEPMENT## are critical and therefore must be recorded. The maintenance transaction must note who last changed a table entry. This can be done by appending fields for the personnel number of the last person to change the entry and the date of the last entry to tables ZEMPLOY## and ZDEPMENT##. Make sure that the same fields are available in both tables for recording the changes by adding these fields to both tables with a substructure ZCHANGE##. Create a new data element for field Lastchangedby, but use an existing domain. Use S_CHDATE as data element for the date of the last change.

What actions are executed on activation in the database?

Note: In a real application, the above enhancement would always cause the standard table maintenance for the two tables to be deactivated. Your own maintenance transactions would instead be created for the table in which the fields

© SAP AG TAW12 3-16

for change logging would be filled internally by the program and not directly by the user.

Creation of such transactions goes beyond the scope of this course. In this course, you will therefore assume that all users themselves (correctly) fill these fields in the standard table maintenance routine.

Start Program BC430_CHECK in Transaction SE38. This program checks whether your solutions are correct and fills the new tables ZEMPLOY## and ZDEPMENT## with sample data needed for later exercises.

© SAP AG TAW12 3-17

Tables in the ABAP Dictionary Solutions

Unit: Tables in the ABAP Dictionary

1-1 The path

Tools → ABAP Workbench → Development → Dictionary or Transaction SE11 takes you to the overview screen of the ABAP Dictionary.

1-1-1 To create table ZEMPLOY##:

1) Mark Database table and enter table name ZEMPLOY## in the corresponding input field.

2) Choose Create.

3) Enter a short text in the maintenance screen for the table.

4) Choose delivery class A and mark Table maintenance allowed.

5) Now choose tab page Fields to go to the maintenance screen for the field definitions. Enter the field names (they need not lie in the customer namespace).

6) Use the given data elements for fields Client, Carrier, First name, Last name, and Currency by entering the names of the data elements in column Field type. Save your entries.

7) Create your own data elements for fields Personnel number, Department code, Area, and Salary. Enter a name (Z<object>##) for the data element in column Field type. Select the name of the data element. The data element definition appears.

8) Enter a short text (component of the F1 help). Now choose tab page Field label and store the texts for the field labels there.

9) You also have to assign the data element a technical description (domain). Select tab page Definition and enter a name (Z<object>##) for your domain there. If the domain is predefined, activate the data element and return (using F3 or ß) to the maintenance screen for the table fields. Otherwise select the domain name. The domain definition appears.

10) Define the short description, data type (for example NUMC), and number of characters (for example,10) there. Activate the domain.

11) Go back one screen (using F3 or ß) to the data element definition and activate your data element.

12) Navigate back one more screen to the field definition. Start again with 7 until all the table fields are defined. Save your table.

13) Define the reference table and reference field for the salary field. Select on the field name and enter the following in the next dialog box:

© SAP AG TAW12 3-18

Reference table: ZEMPLOY##

Reference field: Currency

14) Define the key fields for table ZEMPLOY##. Fields Client, Carrier, and Personnel number uniquely identify an entry. They must, therefore, be marked as key fields. You can do this by marking the Key column following the field name. The key fields must be at the beginning of the field list in this order.

15) Activate the table. The maintenance screen for the technical settings appears automatically:

Since the contents of table ZEMPLOY## do not change frequently, you must choose data class APPL0 (master data). The expected number of records in table ZEMPLOY## is 60,000, so you must choose size category 2. The table should not be either buffered or logged.

ZEMPLOY##

Data class APPL0 (master data)

Size category 2

Buffering Not allowed

Logging No logging

Save the technical settings. Go back to the maintenance screen of the table (F3 or ß). The table is activated.

© SAP AG TAW12 3-19

1-1-2 To create table ZDEPMENT##:

1) to 12) see Solution 1-1-1

13) Define the key fields for table ZDEPMENT##. Fields Client, Carrier, and Department code uniquely identify an entry. They must therefore be marked as key fields. You can do this by marking the Key column following the field name.

14) Activate your table and define the technical settings:

Since the contents of table ZDEPMENT## do not change frequently, you must choose data class APPL0 (master data). The expected number of records in table ZDEPMENT## is defined to be at most 90 entries, so you must choose size category 0. The table should not be either buffered or logged.

ZDEPMENT##

Data class APPL0 (master data)

Size category 0

Buffering Not allowed

Logging No logging

1-2 To document fields Personnel number and Department code:

1) Select to go to the data element in the data element definition. Switch to Change mode with Display <-> Change. Select Documentation or choose Goto à Documentation.

2) Enter a text for the fields and save your entries.

1-3 Create structure ZCHANGE## as follows:

1) In the initial screen of the ABAP Dictionary, mark Data type and enter ZCHANGE## in the corresponding field. Choose Create.

2) Mark Structure in the next dialog box.

3) Enter the field names in column Component and the corresponding data elements in column Component type. Create one field for the personnel number and another one for the date of change. Use data element S_CHDATE for the second field. Create your own data element for the first field, as in Exercise 2-1. Use the domain you created for the personnel number in table ZEMPLOY##.

4) Activate structure ZCHANGE##.

Now insert ZCHANGE## as an include in tables ZEMPLOY## and ZDEPMENT## as follows:

1) Go to the maintenance screen for table ZEMPLOY##.

2) Choose New rows and position the cursor on the first new field.

3) Choose Edit → Include → Insert.

4) In the next dialog box, enter the name ZCHANGE## and choose Continue.

© SAP AG TAW12 3-20

5) Activate the table.

6) You can display the actions that were performed in the database with Utilities → Activation log.

7) Start with step 1) to insert substructure ZCHANGE## in table ZDEPMENT##.

© SAP AG TAW12 4-1

SAP AG 1999

l Indexes

n Primary index and secondary index

n Structure of an index

n Data access using an index

l Table buffering

n Advantages of buffering

n Local table buffers

n Buffering types

n Buffer synchronization

nWhich tables should be buffered?

Performance during Table Access

© SAP AG TAW12 4-2

SAP AG 2002

Course Objectives

At the end of this unit, you will be able to:

l Judge when table accesses can be speeded up by using indexes

l Create indexes in the ABAP Dictionary

l Explain the different buffering types

l Judge when it makes sense to buffer a table and which buffering type you should choose

l Buffer a table using the technical settings

© SAP AG TAW12 4-3

SAP AG 2002

Table SCOUNTER

Index on AIRPORT

MANDT CARRIDCOUNTNUM AIRPORT

001001001001001001001001001001001001001001

LHBAUALHBALHAALHBALHLHBALHLH

000000050000000400000001000000020000000300000007000000010000000300000001 0000000100000004000000020000000600000008

ACAACEBERLCYLHRBERDENFRALCYLGWLHRMUCRTMHAM

AIRPORT P

ACAACEBERBERDENFRAHAMLCYLCYLGWLHRLHRMUCRTM

1236781449105111213

Binary search

Structure of an Index

SELECT * FROM SCOUNTER WHERE AIRPORT = 'LHR'.

MANDT

001001001001001001001001001001001001001001

n An index can be used to speed up the selection of data records from a table. n An index can be considered to be a copy of a database table reduced to certain fields. The data is

stored in sorted form in this copy. This sorting permits fast access to the records of the table (for example using a binary search). Not all of the fields of the table are contained in the index. The index also contains a pointer from the index entry to the corresponding table entry to permit all the field contents to be read.

n When creating indexes, please note: � An index can only be used up to the last specified field in the selection! The fields that are

specified in the WHERE clause for a large number of selections should be in the first position. � Only those fields whose values significantly restrict the amount of data are meaningful in an

index. � When you change a data record of a table, you must adjust the index sorting. Tables whose

contents are frequently changed should not have too many indexes. � Make sure that the indexes on a table are as disjunct as possible.

© SAP AG TAW12 4-4

SAP AG 2002

TABIndex AF2 Z F1 F2 F3

10A3 10 Text

Access with Indexes

Index 0F1 Z

Optimizer

SELECT * FROM TAB WHERE F2 = `10´.

Program

n The database optimizer decides which index on the table should be used by the database to access data records.

n You must distinguish between the primary index and secondary indexes of a table. The primary index contains the key fields of the table. The primary index is automatically created in the database when the table is activated. If a large table is frequently accessed such that it is not possible to apply primary index sorting, you should create secondary indexes for the table.

n The indexes on a table have a three-character index ID. 0 is reserved for the primary index. Customers can create their own indexes on SAP tables; their IDs must begin with Y or Z.

n If the index fields have key function, for example, they already uniquely identify each record of the table, an index can be called a unique index. This ensures that there are no duplicate index fields in the database.

n When you define a secondary index in the ABAP Dictionary, you can specify whether it should be created on the database when it is activated. Some indexes only result in a gain in performance for certain database systems. You can therefore specify a list of database systems when you define an index. The index is then only created on the specified database systems when activated.

© SAP AG TAW12 4-5

SAP AG 2002

Communication system

Database

Data Access using the Buffer

Database interface

SELECT * FROM SBOOK WHERE ...

ABAP programR/3 table buffer

Database processes

Database buffer

n Table buffering increases the performance when the records of the table are read. n The records of a buffered table are read directly from the local buffer of the application server on

which the accessing transaction is running when the table is accessed. This eliminates time-consuming database accesses. The access improves by a factor of 10 to 100. The increase in speed depends on the structure of the table and on the exact system configuration. Buffering, therefore, can greatly increase the system performance.

n If the storage requirements in the buffer increase due to further data, the data that has not been accessed for the longest time is displaced. This displacement takes place asynchronously at certain times which are defined dynamically based on the buffer accesses. Data is only displaced if the free space in the buffer is less than a predefined value or the quality of the access is not satisfactory at this time.

n Entering $TAB in the command field resets the table buffers on the corresponding application server. Only use this command if there are inconsistencies in the buffer. In large systems, it can take several hours to fill the buffers. The performance is considerably reduced during this time.

© SAP AG TAW12 4-6

SAP AG 2002

Table Buffering

Application server 2Application server 1

Table bufferTable buffer

Program Program

Program reads data from a buffered tableRecords are loaded

into the buffer

Database

TAB

n The R/3 System manages and synchronizes the buffers on the individual application servers. If an application program accesses data of a table, the database interfaces determines whether this data lies in the buffer of the application server. If this is the case, the data is read directly from the buffer. If the data is not in the buffer of the application server, it is read directly from the database and loaded into the buffer. The buffer can therefore satisfy the next access to this data.

n The buffering type determines which records of the table are loaded into the buffer of the application server when a record of the table is accessed. There are the following buffering types:

Full buffering: When a record of the table is accessed, all the records of the table are loaded into the buffer. Generic buffering: When a record of the table is accessed, all the records whose left-justified part of the key is the same are loaded into the buffer. Single-record buffering: Only the record that was accessed is loaded into the buffer.

© SAP AG TAW12 4-7

SAP AG 2002

Application server

SELECT * FROM SCOUNTER WHERECARRID = 'LH' AND COUNTNUM = '00000004'.

Buffer contents

0000000100000001000000020000000300000004 000000010000000200000003000000040000000500000006000000070000000800000001

001001001001001001001001001001001001001001

ACAACEBERLCYLHRBERDENFRALCYLGWLHRMUCRTMHAM

Database table SCOUNTERAIRPORTMANDT CARRID COUNTNUM

0000000100000001000000020000000300000004 000000010000000200000003000000040000000500000006000000070000000800000001

AABABABABALHLHLHLHLHLHLHLHUA

001001001001001001001001001001001001001001

ACAACEBERLCYLHRBERDENFRALCYLGWLHRMUCRTMHAM

Full Buffering

AABABABABALHLHLHLHLHLHLHLHUA

n With full buffering, the table is either completely or not at all in the buffer. When a record of the table is accessed, all the records of the table are loaded into the buffer.

n When you decide whether a table should be fully buffered, you must take the table size, the number of read accesses and the number of write accesses into consideration. The smaller the table is, the more frequently it is read and the less frequently it is written, the better it is to fully buffer the table.

n Full buffering is also advisable for tables having frequent accesses to records that do not exist. Since all the records of the table reside in the buffer, it is already clear in the buffer whether or not a record exists.

n The data records are stored in the buffer sorted by table key. When you access the data with SELECT, only fields up to the last specified key field can be used for the access. The left-justified part of the key should therefore be as large as possible for such accesses. For example, if the first key field is not defined, the entire table is scanned in the buffer. Under these circumstances, a direct access to the database could be more efficient if there is a suitable secondary index there.

© SAP AG TAW12 4-8

SAP AG 2002

Application server

Buffer contents

0000000100000002000000030000000400000005000000060000000700000008

LHLHLHLHLHLHLHLH

001001001001001001001001

BERDENFRALCYLGWLHRMUCRTM

Database table SCOUNTERMANDT CARRID COUNTNUM

0000000100000001000000020000000300000004 000000010000000200000003000000040000000500000006000000070000000800000001

AABABABABALHLHLHLHLHLHLHLHUA

001001001001001001001001001001001001001001

ACAACEBERLCYLHRBERDENFRALCYLGWLHRMUCRTMHAM

AIRPORT

SELECT * FROM SCOUNTER WHERECARRID = 'LH' AND COUNTNUM = '00000004'.

Generic Buffering

Generic key

n With generic buffering, all the records whose generic key fields agree with this record are loaded into the buffer when one record of the table is accessed. The generic key is a left-justified part of the primary key of the table that must be defined when the buffering type is selected. The generic key should be selected so that the generic areas are not too small, which would result in too many generic areas. If there are only a few records for each generic area, full buffering is usually preferable for the table. If you choose too large a generic key, too much data will be invalidated if there are changes to table entries, which would have a negative effect on the performance.

n A table should be generically buffered if only certain generic areas of the table are usually needed for processing.

n Client-dependent, fully buffered tables are automatically generically buffered. The client field is the generic key. It is assumed that not all of the clients are being processed at the same time on one application server. Language-dependent tables are a further example of generic buffering. The generic key includes all the key fields up to and including the language field.

n The generic areas are managed in the buffer as independent objects. The generic areas are managed analogously to fully buffered tables. You should therefore also read the information about full buffering.

© SAP AG TAW12 4-9

SAP AG 2002

Buffer contents

00000004 LH001 LCY

Database table SCOUNTER

MANDT CARRID COUNTNUM

0000000100000001000000020000000300000004 000000010000000200000003000000040000000500000006000000070000000800000001

AABABABABALHLHLHLHLHLHLHLHUA

001001001001001001001001001001001001001001

ACAACEBERLCYLHRBERDENFRALCYLGWLHRMUCRTMHAM

AIRPORT

Application serverSELECT SINGLE * FROM SCOUNTER WHERE CARRID = 'LH' AND COUNTNUM = '00000004'.

Single-Record Buffering

n Only those records that are actually accessed are loaded into the buffer. Single-record buffering saves storage space in the buffer compared to generic and full buffering. The overhead for buffer administration, however, is higher than for generic or full buffering. Considerably more database accesses are necessary to load the records than for the other buffering types.

n Single-record buffering is recommended particularly for large tables in which only a few records are accessed repeatedly with SELECT SINGLE. All the accesses to the table that do not use SELECT SINGLE bypass the buffer and directly access the database.

n If you access a record that was not yet buffered using SELECT SINGLE, there is a database access to load the record. If the table does not contain a record with the specified key, this record is recorded in the buffer as non-existent. This prevents a further database access if you make another access with the same key.

n You only need one database access to load a table with full buffering, but you need several database accesses with single-record buffering. Full buffering is therefore generally preferable for small tables that are frequently accessed.

© SAP AG TAW12 4-10

SAP AG 2002

Server 2

Buffer

TAB

SELECT * FROM TAB WHERE FIELD = 'X'.

Server 1

Buffer

Synchronization table

11

22

TAB

Buffer Synchronization 1

n Since the buffers reside locally on the application servers, they must be synchronized after data has been modified in a buffered table. Synchronization takes place at fixed time intervals that can be set in the system profile. The corresponding parameter is rdisp/bufreftime and defines the length of the interval in seconds. The value must lie between 60 and 3600. A value between 60 and 240 is recommended.

n The following example shows how the local buffers of the system are synchronized. A system with two application servers is assumed.

n Starting situation: Neither server has yet accessed records of the table TAB to be fully buffered. The table therefore does not yet reside in the local buffers of the two servers. Timepoint 1: Server 1 reads records from table TAB on the database. Timepoint 2: Table TAB is fully loaded into the local buffer of server 1. Accesses from server 1 to the data of table TAB now use the local buffer of this server.

© SAP AG TAW12 4-11

SAP AG 2002

SELECT * FROM TAB WHERE FIELD = 'Y'.

Server 2

Buffer

TAB

Server 1

Buffer

Synchronization table

33

44

TABTAB

Buffer Synchronization 2

Timepoint 3: Server 2 accesses records of the table. Since the table does not yet reside in the local buffer of server 2, the records are read directly from the database. Timepoint 4: Table TAB is loaded into the local buffer of server 2. Server 2 therefore also uses its local buffer to access data of TAB the next time it reads.

© SAP AG TAW12 4-12

SAP AG 2002

Server 2

Buffer

TAB

DELETE * FROM TAB WHERE FIELD = 'X'.

Server 1

Buffer

Synchronization table

TAB TAB

TAB modified by Server 1

5566

77

Buffer Synchronization 3

Timepoint 5: Server 1 deletes records from table TAB and updates the database. Timepoint 6: Server 1 writes an entry in the synchronization table. Timepoint 7: Server 1 updates its local buffer.

© SAP AG TAW12 4-13

SAP AG 2002

TABSynchronization table

TAB modified by Server 1

SELECT * FROM TAB WHERE FIELD = 'X'.

Server 2

Buffer

Server 1

Buffer

TAB TAB88

Buffer Synchronization 4

Timepoint 8: Server 2 accesses the deleted data records. Since table TAB resides in its local buffer, the access uses this local buffer. � Server 2 therefore finds the records although they no longer exist in the database table. � If the same access were made from an application program to Server 1, this program would

recognize that the records no longer exist. At this time the behavior of an application program depends on the server on which it is running.

© SAP AG TAW12 4-14

SAP AG 2002

Server 2

Buffer

TAB

Server 1

Buffer

Synchronization table

TAB TAB

TAB modified by Server 1

9999

1010

Synchronization

Buffer Synchronization 5

Timepoint 9: The moment of synchronization has arrived. Both servers look in the synchronization table to see if another server has modified one of the tables in its local buffer in the meantime. Timepoint 10: Server 2 finds that table TAB has been modified by Server 1 in the meantime. Server 2 therefore invalidates the table in its local buffer. The next access from Server 2 to data of table TAB therefore uses the database. Server 1 does not have to invalidate the table in its buffer since it itself is the only one to modify table TAB. Server 1 therefore uses its local buffer again the next time to access records of table TAB.

© SAP AG TAW12 4-15

SAP AG 2002

TABSynchronization table

SELECT * FROM TAB WHERE FIELD = 'Y'.

Server 2

Buffer

Server 1

Buffer

TAB TAB

1111

1212

Buffer Synchronization 6

Timepoint 11: Server 2 again accesses records of table TAB. Since TAB is invalidated in the local buffer of Server 2, the access uses the database. Timepoint 12: The table is again loaded into the local buffer of Server 2. The information about table TAB is now consistent again in both servers and the database. n Advantages and disadvantages of this method of buffer synchronization:

� Advantage: The load on the network is kept to a minimum. If the buffers were to be synchronized immediately after each modification, each server would have to inform all other servers about each modification to a buffered table via the network. This would have a negative effect on the performance. � Disadvantage: The local buffers of the application servers can contain obsolete data between the

moments of synchronization. n This means that:

� Only those tables that are written very infrequently (read mostly) or for which such temporary inconsistencies are of no importance may be buffered. � Tables whose entries change frequently should not be buffered. Otherwise there would be a

constant invalidation and reload, which would have a negative effect on the performance.

© SAP AG TAW12 4-16

SAP AG 2002

Unit Summary

l An index helps you to speed up read accesses to a table. An index can be considered a sorted copy of the table that is reduced to the index fields.

l The table buffers reside locally on the application servers.

l Buffering can substantially increase the performance when the records of the table are accessed. Choosing the correct buffering type is important.

l The table buffers are adjusted to changes to the table entries at fixed intervals.

l The more frequently a table is read and the less frequently the table contents are changed, the better it is to buffer the table.

© SAP AG TAW12 4-17

Peformance During Table Access Exercises

Unit: Performance During Table Access

At the conclusion of these exercises, you will be able to:

• Create indexes

• Maintain the buffering attributes of a table

In their daily work, airline employees need fast access to the data in the employee administration tables. In this exercise, access to the data in these tables should be speeded up.

1-1 The combination of first and last names is often used to access the personnel data of an employee. The last name is more often known (that is, specified in the access) than the first name.

Create an index that supports this access. Make sure that the index is created in the database.

1-2 To set up a flight crew, you have to assign employees (pilots and stewards) to flights. Create a table in which the employees involved and their functions can be entered for each flight.

A table with the corresponding structure already exists in the system. Copy this table SFLCREW to table ZFLCREW##. Replace the existing data element for the employee number with your own data element.

Do not forget to activate table ZFLCREW##.

1-3 Reconsider the settings you made for buffering tables ZDEPMENT## and ZFLCREW##. Keep the following information for using these tables in mind:

The carriers have between 10 and 30 departments. Only a few carriers (maximum 3) are administered in the tables. The data about the crews of completed flights are rolled out to an archive file every three months. Table ZFLCREW## therefore has relatively few entries (at most 5,000 per carrier).

Tables ZDEPMENT## and ZFLCREW## are accessed very frequently. Data records are read repeatedly from these tables.

© SAP AG TAW12 4-18

Administrative employees of only one airline work on one application server. The data about the flight crew is only of interest within the airline. Since the airlines share some services, administrative employees of an airline, often have to access departmental data of other airlines.

Start Program BC430_CHECK in Transaction SE38. This program checks whether your solutions are correct and fills the new table ZFLCREW## with sample data needed for later exercises.

If you do the supplementary exercise, only start this program after completing the supplementary exercise.

1-4 Supplementary Exercise: Using an index on the areas might result in a gain in performance when accessing the employee data, for example, if all pilots are frequently selected.

In performance measurements on different database systems it was found there is only a gain in performance for the ADABAS and SQL Server database systems. Create an index and make sure that it is only created on the ADABAS and SQL Server database systems.

© SAP AG TAW12 4-19

Performance During Table Access Solutions

Unit: Performance During Table Access

1-1 The personnel data of the employees is managed in Table ZEMPLOY##. Create an index for this table. It has to contain fields Client, Lastname and Firstname. Since the last name is usually specified and is much more selective than the first name, the last name must be in its index. The order of the fields is then Client, Lastname, and then Firstname.

To create the index:

1) In display mode, go to the maintenance screen of table ZEMPLOY## and choose Indexes.

2) In the next dialog box, confirm that you want to create an index.

3) In the following dialog box, enter a three-place index ID and choose Continue.

4) The maintenance screen for the index appears. Enter a Short description.

5) Choose Table fields. A list of all the fields in the table appears. Select fields Client, Lastname, and Firstname and choose Copy.

6) The fields are copied from the dialog box to the index in that order. If field Firstname is before field Lastname, you have to change the order of the fields. Do this by placing the cursor on the line with field Firstname and choosing Cut. Now place the cursor on the first free line after field Lastname and choose Paste.

7) The index is certainly not a unique index since there can be employees with the same first and last names. There is no reason to create the index only in certain database systems. You should therefore leave the standard settings Non-unique index and Index in all database systems.

8) Activate the index. The index is automatically created in the database.

1-2 To copy table SFLCREW:

1) In the initial screen of the ABAP Dictionary, enter SFLCREW in field Database table. Choose Copy.

2) In the next dialog box, enter the name ZFLCREW## in field to table and choose Continue.

3) In change mode, go to the table maintenance screen and replace data element SEMP_NUM with the data element you created for the employee number.

4) Activate the table.

© SAP AG TAW12 4-20

1-3 You can maintain the buffering settings for the specified tables in their technical settings. To do so, go to the maintenance screen for the table in display mode and choose Technical settings. The desired maintenance screen appears and you can switch to change mode here.

Since the contents of table ZDEPMENT## are rarely changed but frequently read, it is advisable to buffer the table. Choose Buffering switched on. Since there are no restrictions on the access and the table is small, you should select full buffering. Select Fully buffered.

Activate the technical settings of table ZDEPMENT##.

The data of table ZFLCREW## are often read repeatedly. Accesses that change the contents are rare. You should therefore buffer the table. Select Buffering switched on. Usually only the data of one airline is needed on an application server. You should therefore buffer the table generically with the generic key Client and Carrier. Select Generic buffering and choose 2 as the number of generic key fields.

Activate the technical settings of table ZFLCREW##.

1-4 If you do as specified in 3.1, the system displays the index you created in a dialog box. In this dialog box, choose Create. Include fields Client, Carrier, and Area in the index. This is not a unique index either.

To create the index only in the Adabas and SQL Server database systems:

1) Choose For selected database systems.

2) Then select the arrow symbol in this line. Select Selection list. Using the F4 help, select the identifiers for the Adabas (ADA) and SQL Server (MSS) database systems in the list.

3) Choose Continue.

4) Activate the index.

The index is only created in the database if your training system is running on one of the selected database systems.

© SAP AG TAW12 5-1

SAP AG 2002

l Fixed values

l Value table

l What is a foreign key?

l Field assignment using the check field

l Foreign key table / check table

l Semantic attributes of the foreign key

l Text table

Consistency Through Input Checks

© SAP AG TAW12 5-2

SAP AG 2002

Course Objectives

At the end of this unit, you will be able to:

l Create and use fixed values

l Define what a foreign key is

l Apply the conditions for the field assignment of the foreign key

l Know the difference between the value table and the check table

l Create Foreign Key

© SAP AG TAW12 5-3

SAP AG 2002

Domain

Short description

S_CLASS

Flight class

Dictionary: Display domain S_CLASS: Fixed values

Fixed value Short descriptionCY

F

Business ClassEconomy ClassFirst Class

Lower limit Upper limit Short description

Fixed Values

n The domain describes the value range of a field by specifying its data type and field length. If only a limited set of values is allowed, they can be defined as fixed values.

n Specifying fixed values causes the value range of the domain to be restricted by these values. Fixed values are immediately used as check values in screen entries. There is also F4 help.

n Fixed values are only checked in screens. No check is made when data records are inserted in a table by an ABAP program.

n Fixed values can either be listed individually or defined as an interval.

© SAP AG TAW12 5-4

SAP AG 2002

Value Table

Dictionary: Display domain S_CARR_ID

Domain

Short description

S_CARR_ID

Short description of the carrier

Format

Valid values

Value table SCARR

Data type

No. of places

CHAR

3

Character stringsMANDT CARRID CARRNAME CURRCODE401 AA American Airlines USD401 BA British Airways GBP401 LH Lufthansa DEM410 UA United Airlines USD

Table SCARR

n The value range of a field can also be defined by specifying a value table in the domain.

n In contrast to fixed values, however, simply specifying a value table does not cause the input to be checked. There is no F4 help either.

n If you enter a value table, the system can use it to make a proposal for the foreign key definition.

n A value table only becomes a check table when a foreign key is defined. If you refer to a domain with a value table in a field, but no foreign key was defined at field level, there is no check.

© SAP AG TAW12 5-5

SAP AG 2002

Database table SCOUNTER(sales counter)

CARRID (Carrier)

CONNID (Connection)

FLDATE (Date of flight)

COUNTER (Counter)

CUSTOMID (Customer)

Can this flightbe booked at

sales counter 8 ?

Entries to fields of table SBOOK (flight booking):

MANDT CARRID COUNTNUM0000000100000001000000020000000300000004 000000010000000200000003000000040000000500000006000000070000000800000001

AABABABABALHLHLHLHLHLHLHLHUA

001001001001001001001001001001001001001001

ACAACEBERLCYLHRBERDENFRALCYLGWLHRMUCRTMHAM

AIRPORT

Inserting a Data Record

AAAA

00170017

0000000800000008

0000014800000148

25.07.200025.07.2000

n A customer wants to book a flight with American Airlines (AA). This flight with flight number 0017 is to be on July 25, 2000. The booking should be made at counter 8.

n Table SBOOK contains all the flight bookings of the carriers. n Table SCOUNTER contains all the valid counters of the carriers. n If an entry is made in field COUNTER of table SBOOK, you must make sure that only valid

counters can be entered. This means that the counters must be stored in table SCOUNTER. n Question:

Are you allowed to insert the above data record in table SBOOK?

© SAP AG TAW12 5-6

SAP AG 1999

Database table SCOUNTER

MANDT CARRID COUNTNUM0000000100000001000000020000000300000004 000000010000000200000003000000040000000500000006000000070000000800000001

AABABABABALHLHLHLHLHLHLHLHUA

001001001001001001001001001001001001001001

ACAACEBERLCYLHRBERDENFRALCYLGWLHRMUCRTMHAM

AIRPORT CARRID (Carrier)

CONNID (Connection)

FLDATE (Date of flight)

COUNTER (Counter)

CUSTOMID (Customer)

Entries to fields of table SBOOK:

Insertion not allowed!Insertion not allowed!

Violation of the Foreign Key Check

Effect of the foreign key definition:Effect of the foreign key definition:A data record with the contents:A data record with the contents:MANDT = '001', CARRID = 'AA', MANDT = '001', CARRID = 'AA', COUNTNUM = '000000009' does not COUNTNUM = '000000009' does not exist in table SCOUNTER.exist in table SCOUNTER.

AAAA

00170017

0000014800000148

25.07.200025.07.2000

000000008000000008

n The flight cannot be booked because American Airlines (AA) does not have a counter 8. n No data record is selected in table SCOUNTER for the entries in the example. The entry for table

SBOOK is rejected. n In the ABAP Dictionary, such relationships between two tables are called foreign keys and they

must be defined explicitly for the fields. n Foreign keys are used to ensure that the data is consistent. Data that has been entered is checked

against existing data to ensure that it is consistent.

© SAP AG TAW12 5-7

SAP AG 2002

Foreign Key Fields / Check Fields

Key fields

MANDT CARRID COUNTNUM AIRPORT

Foreign key table SBOOK

MANDT CARRID CONNID FLDATE CUSTOMID CANCELED

Foreign key fields

Check field

... COUNTER ...

Check table SCOUNTER

EXAMPLE: n In this example, the foreign key table is table SBOOK. The purpose of the foreign key is to ensure

that only valid counters of carriers can be assigned to a booking. Check table SCOUNTER contains exactly this information. Each counter is identified with three key fields in this table: MANDT, CARRID, and COUNTNUM.

n In order to define the foreign key, these three fields are assigned to the fields of the foreign key table (foreign key fields) with which the input to be checked is entered on the screen. In table SBOOK, these are the fields: MANDT, CARRID, COUNTER. The entry is accepted if it represents a valid counter; otherwise the system will reject it.

n The foreign key is defined for field SBOOK-COUNTER (check field), which means that the entry in this field is checked. Field COUNTER is therefore called the check field for this foreign key.

A foreign key is defined for field COUNTER, table SBOOK, resulting in the following field assignment:

Check table Foreign key table SCOUNTER-MANDT SBOOK-MANDT SCOUNTER-CARRID SBOOK-CARRID SCOUNTER-COUNTNUM SBOOK-COUNTER

© SAP AG TAW12 5-8

SAP AG 2002

Data Consistency through Foreign Keys

MANDT CARRID CONNID ...800

800

800

800

AA

AA

Rome

Rome

0017

0064

0555

0788

MANDT CARRID ...800

800

800

800

AA

AC

AF

Rome

SCARR: Check table = ref. obj. SPFLI: Foreign key table = dep. obj.

SPFLI-CARRIDSPFLI-MANDT

Carrier

Flight number

Detailmaint.

AB

0020

Check field

Foreign key fields

STOPSTOP

n A combination of fields in a table is called a foreign key if this field combination is the primary key of another table.

n A foreign key links two tables. n The check table is the table whose key fields are checked. This table is also called the referenced

table. n An entry is to be written in the foreign key table. This entry must be consistent with the key fields of

the check table. n The field of the foreign key table to be checked is called the check field. n Foreign keys can only be used in screens. Data records can be written to the table without being

checked using an ABAP program. n Example: A new entry is to be written in table SPFLI (flight schedule). There is a check whether the

airline carrier entered is stored in table SCARR (carrier) for field SPFLI-CARRID. The record is only copied to table SPFLI (foreign key table) if this is the case. A foreign key is defined for field SPFLI-CARRID (check field), for example, the checks are on this field. The corresponding check table is table SCARR with the primary key fields MANDT and CARRID.

© SAP AG TAW12 5-9

SAP AG 2002

Foreign Key Definitions in the Check Field

Key fields

Table SPFLI

MANDT ......Departure airport

with check table:SAIRPORT

Table SAIRPORT

MANDT ......Airport

Domain S_AIRPIDDomain S_AIRPIDValue table SAIRPORTValue table SAIRPORT

Data element S_AIRPORTData element S_AIRPORT Data element S_FROMAIRPData element S_FROMAIRP

Foreign key relationship to the check field Departure Airport

n In the ABAP Dictionary, the same domain is required for the check field and referenced key field of the check table so that you do not compare fields with different data types and field lengths. Domain equality is essential. Different data elements can be used, but they must refer to the same domain.

n The requirement for domain equality is only valid for the check field. For all other foreign key fields, it is sufficient if the data type and the field length are equal. You nevertheless should strive for domain equality. In this case, the foreign key will remain consistent if the field length is changed because the corresponding fields are both changed. If the domains are different, the foreign key will be inconsistent if, for example, the field length is changed.

n If the domain of the check field has a value table, you can have the system make a proposal with the value table as check table. In this case, a proposal is created for the field assignment in the foreign key.

n CAUTION! The example that a domain that itself has table SAIRPORT as value table is used following field SAIRPORT-Airport is correct! However, a foreign key is never defined on this field (avoiding a loop).

© SAP AG TAW12 5-10

SAP AG 2002

Check Table not Equal to Value Table

Table SBUSPART

MANDT BUSPARTNUM ...

Domain S_Domain S_BUSPANUMBUSPANUMValue table SBUSPARTValue table SBUSPART

MANDT AGENCYNUM ...

Table STRAVELAG

Foreign key table SBOOK

MANDT CARRID CANCELED... AGENCYNUM ...

n In the above example for the foreign key definition for field SBOOK-AGENCYNUM, the system proposal is as follows based on the value table in the domain: Check table: SBUSPART Field assignment: Check table Foreign key table SBUSPART-MANDT SBOOK-MANDT SBUSPART-BUSPARTNUM SBOOK-AGENCYNUM

n This proposal does not do what you want it to do: Table SBUSPART contains all the business partners of airline carriers. However, only agencies are allowed for field SBOOK-AGENCYNUM. Table SBUSPART therefore contains invalid data for this field. The system proposal is therefore incorrect! The correct check table is table STRAVELAG. It is a subset of table SBUSPART due to its foreign key definition on field AGENCYNUM. You must overwrite the system proposal with table STRAVELAG. If you do not know the correct check table, the system can help you by listing all the tables in question. This includes all the tables that have a key field with domain S_ BUSPANUM.

© SAP AG TAW12 5-11

SAP AG 2002

Semantic Attributes

1:C

1:N1:1

1:CN

Cardinality

C

C

C

C

F

F

F

F

n The cardinality describes the foreign key relationship with regard to how many records of the check table are assigned to records of the foreign key table. The cardinality is always defined from the point of view of the check table.

n The type of the foreign key field defines whether or not the foreign key field identifies a table entry. This means that the foreign key fields are either key fields or they are not key fields or they are a special case, namely the key fields of a text table.

n There are the following kinds of foreign key fields: � Not specified: No information about the kind of foreign key field can be given. � No key fields / candidates: The foreign key fields are neither primary key fields of the foreign

key table nor do they uniquely identify a record of the foreign key table (key candidates). The foreign key fields therefore do not (partially) identify the foreign key table. � Key fields / candidates: The foreign key fields are either primary key fields of the foreign key

table or they uniquely identify a record of the foreign key table (key candidates). The foreign key fields therefore (partially) identify the foreign key table. � Key fields of a text table: The foreign key table is a text table of the check table, for example, the

key of the foreign key table only differs from the key of the check table in an additional language key field. This is a special case of the category Key fields / candidates.

© SAP AG TAW12 5-12

SAP AG 2002

Text Table

Text table SMEALT

MEAL-NUMBER

MANDT CARRID LANGUAGE TEXT

Table SMEAL

MANDT CARRID MEAL-TYPE

MEAL-NUMBER

Key fieldsKey fields

Foreign Key Relationship with Check Table SMEALType of foreign key fields: key fields of a text table

n Table SMEAL contains the meals served to the passengers during a flight. The meal names are maintained in table SMEALT.

n Table SMEALT is the text table for table SMEAL since the key of SMEALT consists of the key of SMEAL and an additional language key field (field with data type LANG).

n Table SMEALT can contain explanatory text in several languages for each key entry of SMEAL. n To link the key entries with the text, the text table SMEALT must be linked with table SMEAL using

a foreign key. Key fields of a text table must be chosen for the type of the foreign key fields. n The foreign key relationship is defined from SMEALT to SMEAL. n Only one text table can be created for a table.

© SAP AG TAW12 5-13

SAP AG 2002

Unit Summary

l Two ways to check the data consistency were introduced in this unit:

n Fixed values (static)

n Foreign keys (dynamic)

l The fixed values are stored in the domain.

l The foreign key permits you to check the values you enter against existing data.

l The foreign key relationship is maintained for the check field (field of the foreign key table).

l The check field must be assigned to a check table key field having the same domain.

© SAP AG TAW12 5-14

Consistency Through Input Checks Exercises

Unit: Consistency through Input Checks

At the conclusion of these exercises, you will be able to:

• Create fixed values

• Set value tables to the correct context

• Define foreign keys

• Use the above mechanism to ensure that the data is consistent

When you enter or change the employee master data, only consistent data, for example, valid airline carriers, departments, areas, etc., should be allowed. This will be implemented in the next exercise.

1-1 The employees of the airlines are divided into administration personnel (A), flight personnel (F) and service personnel (S). They are assigned to activity areas A, F or S accordingly. Make sure that only valid activity areas can be entered in table ZEMPLOY##.

1-2 Define suitable foreign keys for tables ZEMPLOY##, ZDEPMENT##, and ZFLCREW##. Use the tables of the flight model or tables T000 (client) and SCURX (currency code) as well as your tables to define the foreign keys. Define a foreign key check for each of the following fields:

ZEMPLOY##-Client

ZEMPLOY##-Carrier

ZEMPLOY##-Department code

ZEMPLOY##-Currency

and

ZDEPMENT##-Client

ZDEPMENT##-Carrier

and

ZFLCREW##-Emp_num

© SAP AG TAW12 5-15

Maintain the data for table ZEMPLOY## and test the effect of your foreign key relationships.

1-3 Some employees of carriers work in travel agencies in order to sell flights for their companies there. Enhance table ZEMPLOY## with a field that documents the travel agency where each employee works.

Enhance table ZEMPLOY## accordingly and define the foreign key relationship.

The table of all travel agencies is called STRAVELAG.

1-4 Each department of an airline has a head of department. The assignment between the department and the head of the department should be mapped in the flight model. Enhance table ZDEPMENT## with field Dephead. Define a suitable foreign key for this field.

Use the two-step domain concept.

1-5 Create a text table ZDEPMENTT## for table ZDEPMENT## to explain the department code for the employees of the carriers in all countries.

Create the corresponding table and use data elements SPRAS and S_TEXT for the field definition.

Define the required foreign key relationships.

© SAP AG TAW12 5-16

Consistency Through Input Checks Solutions

Unit: Consistency through Input Checks

1-1 Call the domain maintenance screen for field ZEMPLOY##-Area. You can do this by navigating from the table maintenance screen to the corresponding data element and from here to the domain. Choose tab page Value range and enter the following fixed values:

Fixed value Short description

A Administration personnel

F Flight personnel

S Service personnel

Activate your domain.

1-2 To maintain the individual foreign keys, call the maintenance routine for the particular tables. Choose tab page Fields.

Create foreign key ZEMPLOY##-Client as follows:

1) Place the cursor on field ZEMPLOY##-Client. Select Foreign key or choose Goto → Foreign key.

2) Since you are using domain MANDT for field ZEMPLOY-Client, the system proposes value table T000 as check table.

3) Have the system make a proposal for the foreign key definition. Check the proposal. The following fields must be assigned:

Check table CkTabFld For. key table For. key fld

T000 MANDT ZEMPLOY## Client

4) Enter a short text and define the semantic attributes as follows:

Type of foreign key fields: key fields / candidates

Cardinality: 1:CN

5) Save your foreign key.

Create foreign key ZEMPLOY##-Carrier as follows:

© SAP AG TAW12 5-17

1) Place the cursor on field ZEMPLOY##-Carrier. Select Foreign key or choose Goto → Foreign key.

2) Since you are using domain S_CARR_ID for field ZEMPLOY-Carrier, you can use value table SCARR for the foreign key definition.

3) Have the system make a proposal for the foreign key definition. Check the proposal. The following fields must be assigned:

Check table ChkTablFld For. key table Foreign key field

SCARR MANDT ZEMPLOY## Client

SCARR CARRID ZEMPLOY## Carrier

4) Enter a short text and define the semantic attributes as follows:

Type of foreign key fields: key fields / candidates

Cardinality: 1:CN

5) Save your foreign key.

Create foreign key ZEMPLOY##-Department code as follows:

1) To get a proposal for the foreign key definition, you must change the domain for field ZEMPLOY##-Department code. This is not absolutely necessary for later foreign key definitions, but makes the definition easier. Enter value table ZDEPMENT## in the domain for this field and activate the domain.

2) Place the cursor on field ZEMPLOY##-Department code. Select Foreign key or choose Goto à Foreign key.

3) Since you are using the domain of field ZDEPMENT##-Department code for field ZEMPLOY-Department code, you can use value table ZDEPMENT## for the foreign key definition.

4) Have the system make a proposal for the foreign key definition. Check the proposal. The following fields must be assigned:

Check table ChkTablFld For. key table Foreign key field

ZDEPMENT## Client ZEMPLOY## Client

ZDEPMENT## Carrier ZEMPLOY## Carrier

ZDEPMENT## Department code ZEMPLOY## Department code

5) Enter a short text and define the semantic attributes as follows:

Type of foreign key fields: non-key-fields / candidates

Cardinality: 1:CN

6) Save your foreign key.

© SAP AG TAW12 5-18

Create foreign key ZEMPLOY##-Currency as follows:

1) Place the cursor on field ZEMPLOY##-Currency. Select Foreign key or choose Goto → Foreign key.

2) Since you are using domain S_CURR for field ZEMPLOY##-Currency, you can use value table SCURX for the foreign key definition.

3) Have the system make a proposal for the foreign key definition. Check the proposal. The following fields must be assigned:

Check table ChkTablFld For. key table For. key fld

SCURX CURRKEY ZEMPLOY## Currency

4) Enter a short text and define the semantic attributes as follows:

Type of foreign key fields: non-key-fields / candidates

Cardinality: 1:CN

5) Save your foreign key.

Create foreign key ZDEPMENT##-Client as follows:

See foreign key ZEMPLOY##-Client.

Create foreign key ZDEPMENT##-Carrier as follows:

See foreign key ZEMPLOY##-Carrier.

Create foreign key ZFLCREW##-Emp_num as follows:

1) Place the cursor on field ZFLCREW##-Emp_num. Select Foreign key or choose Goto → Foreign key.

2) The check table is table ZEMPLOY##. If you stored this table as a value table for the domain for the personnel number, the system will make this proposal. If not, you have to enter it yourself. You can copy the system proposal in the field allocation of the foreign key. The cardinality is 1:CN and the foreign key fields are key fields / candidates.

In the maintenance screen for table ZEMPLOY## choose Utilities→ Table contents → Create entries.

Enter data and check whether your foreign key functions correctly using the F4 help.

1-3 Create a new field Agency in your table ZEMPLOY## as follows:

1) Navigate to the field maintenance screen for table ZEMPLOY##. Insert a new field Agency in the field list (select New rows). In the maintenance screen for table STRAVELAG you can see that the suitable data element is called S_AGNCYNUM. Assign this data element to your new field ZEMPLOY##-Agency.

2) Position the cursor on the field Agency and have the system make a proposal for the foreign key definition.

© SAP AG TAW12 5-19

3) Check the proposal. The check table is SBUSPART. This check table is not correct since it contains all the business partners of carriers and not just agencies.

4) The correct check table is STRAVELAG, which it contains the agencies the carriers work with.

5) You can improve understanding by looking at the definition of table STRAVELAG in a second session. Field AGENCYNUM has a foreign key with check table SBUSPART. This means that table STRAVELAG is a subset of table SBUSPART. In the foreign key definition for ZEMPLOY##-Agency, overwrite entry SBUSBART in the input field Check table with STRAVELAG.

6) Select Copy. The system recognizes the change in the check table and suggests that it create a proposal. Accept this offer and select the proposal. The following fields must be assigned:

Check table ChkTablFld For. key table For. key fld

STRAVELAG MANDT ZEMPLOY## Client

STRAVELAG AGENCYNUM ZEMPLOY## Agency

7) Enter a short description. Enter cardinality 1:CN and indicate that the foreign key fields are not key fields / candidates. Choose Copy.

8) Activate the table.

9) In the maintenance screen for table ZEMPLOY##, choose Utilities → Table Contents → Create Entries.

Verify your foreign key using the F4 help.

1-4 In our model, people are identified by their personnel number. Therefore, the new field to be added to table ZDEPMENT## must contain personnel numbers (and not names). The field should therefore refer to the domain for personnel numbers that you created in the first exercise. Since the person to be managed in this case has a special role, you should create a new data element and not use the one already created for the personnel number. You can either first create the data element and then maintain the table, or create the data element from the table maintenance screen with forward navigation. The second way is described below:

1) Go to change mode in the maintenance screen for table ZDEPMENT##. Select tab page Fields.

2) Choose New rows.

3) Enter the new field directly following the existing fields by entering a suitable field name in the first column and entering a name for the data element to be created in column Field type.

4) Save the table definition.

5) Select the name of the new data element to be created. Confirm that you want to create a data element.

© SAP AG TAW12 5-20

6) Enter a short text for the data element. Enter the domain name that you already created for the personnel number in field Domain.

7) Select page Field label and enter the corresponding text there.

8) Activate the data element. Go back to the maintenance screen for table ZDEPMENT## by choosing Back.

9) Create the foreign key for the new field in the usual manner. The check table is table ZEMPLOY##. If you stored this table as a value table for the domain for the personnel number, the system will make this proposal. If not, you have to enter it yourself. You can copy the system proposal in the field allocation of the foreign key. The cardinality is 1:CN and the foreign key fields are non key fields / candidates.

10) Activate the table.

1-5 Create your text table ZDEPMENTT## as follows:

1) Copy table ZDEPMENT## to table ZDEPMENTT##.

2) Navigate to the field maintenance screen for table ZDEPMENTT##. Delete all the fields that are not key fields. Create the following new fields:

Field name Data element Data type, Length

Language SPRAS LANG

Description S_TEXT CHAR40

Field ZDEPMENT##-Language must be a key field.

3) The foreign keys for fields ZDEPMENTT##-Client and ZDEPMENTT##-Carrier were already correctly defined by copying. You still have to define the foreign keys of fields ZDEPMENTT##-Department code and ZDEPMENTT##-Language.

4) Place the cursor on field ZDEPMENTT##-Department code. Select Foreign key or choose Goto à Foreign key.

5) Since you are using the domain of field ZDEPMENT##-Department code for field ZDEPMENTT##-Department code, you can use value table ZDEPMENT## for the foreign key definition.

6) Have the system make a proposal for the foreign key definition. Check the proposal. The following fields must be assigned:

Check table ChkTablFld For. key table For. key fld

ZDEPMENT## Client ZDEPMENTT## Client

ZDEPMENT## Carrier ZDEPMENTT## Carrier

ZDEPMENT## Department code ZDEPMENTT## Department code

© SAP AG TAW12 5-21

7) Enter a short text and define the semantic attributes as follows:

Type of foreign key fields: key fields of a text table

Cardinality: 1:CN

8) Save your foreign keys.

9) Place the cursor on field ZDEPMENTT##-Language. Select Foreign key or choose Goto → Foreign key.

10) Since you are using domain SPRAS for field ZDEPMENTT##-Language, you can use value table T002 for the foreign key definition.11) Have the system make a proposal for the foreign key definition. Check the proposal. The following fields must be assigned:

Check table ChkTablFld For. key table Foreign key field

T002 SPRAS ZDEPMENTT## Language

11) Enter a short text and define the semantic attributes as follows:

Type of foreign key fields: key fields / candidates

Cardinality: 1:CN

12) Save your foreign key.

13) Activate the table.

© SAP AG TAW12 6-1

SAP AG 1999

l Activation of ABAP Dictionary objects

l Handling of dependent objects

l Where-used list and R/3 Repository Information System as seen by the ABAP Dictionary

Dependencies of ABAP Dictionary Objects

© SAP AG TAW12 6-2

SAP AG 2002

Course Objectives

At the end of this unit, you will be able to:

l Differentiate between the active and inactive version of an ABAP Dictionary object.

l Describe the mechanism for handling dependent objects in the ABAP Dictionary

l Explain how the Repository Information System and the Where-used list for ABAP Dictionary objects function

© SAP AG TAW12 6-3

SAP AG 2002

Active and Inactive Versions

Active version Inactive version

Active version

Active version

Field 1 Field 2 Field 3 Field 1 Field 2 Field 3 Field 4

Field 1 Field 2 Field 3 Field 4

Activate

Add Field 4 in the ABAP Dictionary

Field 2 Field 3Field 1

n During development, you sometimes need to change an (active) object already used by the system. Such changes are supported in the ABAP Dictionary by separating the active and inactive versions.

n The active version of an ABAP Dictionary object is the version that the components of the runtime environment (for example ABAP processor, database interface) access. This version is not initially changed.

n An inactive version is created when an active object is changed. The inactive version can be saved without checking. It has no effect on the runtime system.

n At the end of the development process, the inactive version can be made the active version. This is done by activation. The inactive version of the object is first checked for consistency. If it is consistent, the inactive version replaces the active one. From now on, the runtime system uses the new active version.

n The above example shows how the object status changes. An active structure contains three fields. A field is added to this structure in the ABAP Dictionary. After this action, there is an active version with three fields and an inactive version with four fields. During activation, the active version is overwritten with the inactive version. The inactive version thus becomes the active version. After this action there is only the active version with four fields.

© SAP AG TAW12 6-4

SAP AG 2002

Runtime Objects

StructureInformation aboutthe structure

Field information

Runtime objectof the structure

Data elements

Field 2 Field 3Field 1

ABAPInterpreter

Data Data element 1element 1

Data Data element 2element 2

Data Data element 3element 3

Domain 1Domain 1 Domain 2Domain 2 Domain 3Domain 3

n The information about a structure (or table) is distributed in the ABAP Dictionary in domains, data elements, and the structure definition. The runtime object (nametab) combines this information into a structure in a form that is optimized for access from ABAP programs. The runtime object is created when the structure is activated.

n The runtime objects of the structures are buffered so that the ABAP runtime system can quickly access this information.

n The runtime object contains information about the overall structure (for example, number of fields) and the individual structure fields (field name, position of the field in the structure, data type, length, number of decimal places, reference field, reference table, check table, conversion routine, etc.).

n The runtime object of a table contains further information needed by the database interface for accessing the table data (client dependence, buffering, key fields, etc.).

n Runtime objects are created for all ABAP Dictionary objects that can be used as types in ABAP programs. These are data elements, table types, and views, as well as structures and tables.

© SAP AG TAW12 6-5

SAP AG 2002

Handling of Dependent Objects

Structure 3Table 1Structure 2Structure 1

Table 2

includes

Domain Domain

Data element 1Data element 1 Data element 2Data element 2 Data element 3Data element 3

n If an object that is already active is modified, this can affect other objects that use it (directly or indirectly). These objects using another object are called dependent objects. On the one hand, it might be necessary to adjust the runtime objects of these dependent objects to the changes. On the other hand, a change might sometimes make a dependent object inconsistent.

n For this reason, the dependent objects are determined and activated (if necessary) when an active object is activated. The active versions of the dependent objects are activated again. In particular, new and inactive versions of objects using the changed object are not changed.

n Example: When you change a domain, for example, its data type, all the data elements, structures, and tables referring to this domain must be activated again. This activation is automatically triggered when the domain is activated. This ensures that all affected runtime objects are adjusted to the changed type information.

n If an ABAP Dictionary object has a table as dependent object, its database object as well as its runtime object might have to be adjusted when the dependent object is activated. The method used here will be discussed in the next unit.

© SAP AG TAW12 6-6

SAP AG 2002

Where-Used Lists

Use

Where-used lists

Program 1 Program 2

Structure 3Table 1Structure 2Structure 1

DomainDomain

Table 2

Data element 1Data element 1 Data element 2Data element 2 Data element 3Data element 3

n Changing an ABAP Dictionary object might also affect its dependent objects. Before making a critical change (such as changing the data type or deleting a field), you should define the set of objects affected in order to estimate the implications of the planned action.

n There is a Where-used list for each ABAP Dictionary object with which you can find all the objects that refer to this object. You can call the Where-used list from the maintenance transaction of the object.

n You can find direct and indirect usages of an ABAP Dictionary object with the where-used list. You also have to define which usage object types should be included in the search (for example, all structures and tables using a data element). You can also search for usages that are not ABAP Dictionary objects (for example, all programs using a table). The search can also be limited by development class or user namespace.

n If an object is probably used by several objects, you should perform the search in the background.

© SAP AG TAW12 6-7

SAP AG 2002

Show all objects of type Xwith attribute Y

Show all objectsof type X that

were changed by user Y at time DDMMYYYY

Show all objects of type Xthat use object Y

Show all table fieldswith check table X

Information aboutInformation aboutrelationshipsrelationshipsbetween tablesbetween tables Proof of changeProof of change

WhereWhere--used list used list Search by attributeSearch by attribute

ABAPABAPDictionaryDictionary

? ?

? ?

The Repository Information System ABAP Dictionary

n The Repository Information System ABAP Dictionary is part of the general Repository Information System. It helps you search for ABAP Dictionary objects and their users.

n The Where-used list for Repository objects can be called from the information system. The information system also enables you to search for objects by their attributes.

n In addition to the object-specific search criteria (for example, buffering type for tables), you can search for all objects by development class, short description or author, and date of last change.

n The object lists created by the Repository Information System are entirely integrated in the ABAP Workbench. They permit you to navigate directly to the maintenance transactions of the objects found.

© SAP AG TAW12 6-8

SAP AG 2002

Unit Summary

l When an object is activated, the inactive version becomes the active version (after a check). The old active version is overwritten.

l When an object that is already active is activated, any active dependent objects are also activated. The runtime object and the database object of these dependent objects are also updated.

l The Where-used list can be used to find all the Repository objects that use an ABAP Dictionary object.

l You can find ABAP Dictionary objects by their attributes in the Repository Information System.

In the ABAP Dictionary there is an active and an inactive version of an object. The runtime system uses the active version and the development process edits the inactive version.

© SAP AG TAW12 6-9

Dependencies of ABAP Dictionary Objects Exercises

Unit: Dependencies of ABAP Dictionary Objects

At the conclusion of these exercises, you will be able to:

• Enhance tables and structures with fields

• Use the R/3 Repository Information System and the Where-used list for ABAP Dictionary objects

Information about the head of the department should be stored in the employee management system. The change log should also be made more detailed. This exercise makes the appropriate enhancements to the tables and structures.

1-1 The change log for tables ZEMPLOY## and ZDEPMENT## is not precise enough. In addition to the person who made the last change and the date of this change, you also want to record the time of the last change. Have a suitable field inserted in both tables as easily as possible. Use data element S_TIME.

Make sure that the field is inserted in both tables. Check the activation log of the tables and structures involved.

Start Program BC430_CHECK in Transaction SE38. It checks whether your solutions are correct.

1-2 Create a list of the following ABAP Dictionary objects:

1-2-1 All domains with fixed values whose names begin with Z.

1-2-2 All table fields that use data element S_FNAME.

1-2-3 All tables of the flight model (development class BC_DATAMODEL) that have delivery class A.

1-3 Determine all the programs that use table SFLIGHT.

© SAP AG TAW12 6-10

1-4 What are the data elements created by your neighbors called?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

© SAP AG TAW12 6-11

Dependencies of ABAP Dictionary Objects Solutions

Unit: Dependencies of ABAP Dictionary Objects

1-1 The fields for the change log can be found in the include structure ZCHANGE##. The new field should therefore be inserted in this structure. The field is automatically inserted in tables ZEMPLOY## and ZDEPMENT## using the include mechanism. Proceed as follows:

1) In the initial screen of the ABAP Dictionary, select Data type and enter ZCHANGE## in the corresponding field. Choose Change.

2) Select on tab page Components. Enter the name for the new field in the first free row of the component list and enter S_TIME in column Component type.

3) Activate the structure.

4) With Utilities → Activation log you can find the activation log of the structure. You can see here that tables ZEMPLOY## and ZDEPMENT## are activated as dependent objects and were enhanced with the new field.

5) Go to display mode in the maintenance screen for table ZEMPLOY## (or ZDEPMENT##). Choose Utilities → Table contents → Create entries. You can see here that the table was really enhanced with the corresponding field.

1-2 All the exercises can be solved with the Repository Information System. You can do this from the initial screen of the ABAP Dictionary with Environment → Repository Information System. Expand the nodes for the ABAP Dictionary.

1) Expand the node Basic objects. Select Domains. In the selection screen, enter Z* in the first field. Choose All selections. In the enhanced selection screen, select Only domains with fixed values. You can create the desired list with Execute.

2) Choose Back twice to return to the initial screen of the Repository Information System. Expand the Fields node. Select Table fields. Choose All selections and enter S_FNAME in field Data element. You can create the desired list with Execute.

3) Choose Back twice to return to the initial screen of the Repository Information System. Note Basic objects are still expanded. Select Database tables. Enter development class BC_DATAMODEL and (after choosing All selections) delivery class A in the selection screen. You can create the desired list with Execute.

© SAP AG TAW12 6-12

1-3 Go to the initial screen of the ABAP Dictionary. Choose Database table and enter SFLIGHT in the corresponding field. Choose Where-used list. The usage in programs is already indicated (alone) in the next dialog box. You can create the desired list with Execute.

1-4 You can create the desired list again in the Repository Information System ABAP Dictionary. Expand the node Basic objects and select Data elements. You can define your neighbor's data elements with either a pattern search for the name (if your neighbors adhered to the given naming convention) or with Last changed by (after choosing All selections). If you have two groups of neighbors, you have to use Multiple selection. You can restrict the selection with the date of the last change (the last change should be no earlier than the beginning of the course) at least in the first case (naming convention).

© SAP AG TAW12 7-1

SAP AG 1999

l Changes to database tables

l Effect of changes to the table structure

l Table conversion

l Possible problems during conversions

l Append structures

Changes to Database Tables

© SAP AG TAW12 7-2

SAP AG 2002

At the end of this unit, you will be able to:

l Make changes to tables

l Estimate the effect of these changes on the database

l Convert tables

l Continue terminated conversions

l Add customer fields to SAP standard tables by means of append structures without modifications

Course Objectives

© SAP AG TAW12 7-3

SAP AG 1999

ABAP Dictionary

Changes to Tables

Active versioninactive version

Field 1 Field 2 Field 3

Field 2 Field 3Field 1 Field 4

Field 2 Field 3Field 1

Database

n Correct access by ABAP programs to a database table is only possible if the runtime object of the table is consistent with the structure of the table in the database. Each time the table is changed in the ABAP Dictionary, you must check if the database structure of the table must be adjusted to the changed ABAP Dictionary definition of the table when it is activated (when the runtime object is rewritten).

n The database structure does not have to be altered for certain changes to the ABAP Dictionary. For example, you do not have to change the database structure when the order of the fields in the ABAP Dictionary is changed (other than for key fields). In this case the changed structure is simply activated in the ABAP Dictionary and the database structure remains unchanged.

© SAP AG TAW12 7-4

SAP AG 1999

How is the Structure Adjusted?

Field 1 Field 2 Field 3

Active version

Inactive versionDelete, create again

or

Change catalog for the DB (ALTER TABLE)

or

Convert the table

Field 2 Field 3Field 1

Field 2 Field 3Field 1 Field 4

Does the table contain data?

What databasesystem is used?

What change was made?

n The database table can be adjusted to the changed definition in the ABAP Dictionary in three different ways: � By deleting the database table and creating it again. The table on the database is deleted, the

inactive table is activated in the ABAP Dictionary, and the table is created again on the database. Data existing in the table is lost. � By changing the database catalog (ALTER TABLE). The definition of the table on the database is

simply changed. Existing data is retained. However, indexes on the table might have to be built again. � By converting the table. This is the most time-consuming way to adjust a structure.

n If the table does not contain any data, it is deleted in the database and created again with its new structure. If data exists in the table, there is an attempt to adjust the structure with ALTER TABLE. If the database system used is not able to do so, the structure is adjusted by converting the table.

© SAP AG TAW12 7-5

SAP AG 1999

Conversion Process 1

TAB ~ 0

TAB ~ A11

Field 1NUMC, 6

Field 2CHAR, 8

Field 3CHAR, 60

000100001200003000

1111A000222B100030B20

Text1...Text2 ...Text3 ...

TAB

Active version of TAB

Field 2CHAR, 8

Field 3CHAR, 60

Field 1NUMC,6

Inactive version of TAB

Field 2CHAR, 8

Field 1NUMC,6

Field 3CHAR, 30

n The following example shows the steps necessary during conversion. n Starting situation: Table TAB was changed in the ABAP Dictionary. The length of field 3 was

reduced from 60 to 30 places. n The ABAP Dictionary therefore has an active (field 3 has a length of 60 places) and an inactive

(field 3 still has 30 places) version of the table. n The active version of the table was created in the database, which means that field 3 currently has 60

places in the database. A secondary index with the ID A11, which was also created in the database, is defined for the table in the ABAP Dictionary.

n The table already contains data.

© SAP AG TAW12 7-6

SAP AG 2002

Conversion Process 2

QCMTAB

Rename TAB to QCMTAB

Delete indexes

Field 1NUMC, 6

Field 2CHAR, 8

Field 3CHAR, 60

1111A000222B100030B20

Text1...Text2 ...Text3 ...

TAB is locked

TAB ~ A11

TAB ~ 0Field 1

NUMC, 6Field 2

CHAR, 8Field 3

CHAR, 60

000100001200003000

1111A000222B100030B20

Text1...Text2 ...Text3 ...

22

Active version of TAB

Field 2CHAR, 8

Field 3CHAR, 60

Field 1NUMC,6

Inactive version of TAB

Field 2CHAR, 8

Field 1NUMC,6

TAB locked11

TAB

Field 3CHAR, 30

000100001200003000

Step 1: The table is locked against further structure changes. If the conversion terminates due to an error, the table remains locked. This lock mechanism prevents further structure changes from being made before the conversion has been completed correctly. Data could be lost in such a case. Step 2: The table in the database is renamed. All the indexes on the table are deleted. The name of the new (temporary) table is defined by the prefix QCM and the table name. The name of the temporary table for table TAB is therefore QCMTAB.

© SAP AG TAW12 7-7

SAP AG 2002

Conversion Process 3

Activate in theABAP Dictionary

Field 2CHAR, 8

Field 1NUMC, 6

Field 2CHAR, 8

Field 3CHAR, 60

000100001200003000

1111A000222B100030B20

Text1...Text2 ...Text3 ...

QCMTABQCM8TAB

Field 1NUMC, 6

Field 3CHAR, 30

33

Active version of TAB

Field 2CHAR, 8

Field 3CHAR, 60

Field 1NUMC,6

Inactive version of TAB

33

TAB is created in the DB with the name QCM8TAB

Field 2CHAR, 8

Field 1NUMC,6

Field 3CHAR, 30

TAB locked

TAB ~ 0

Step 3: The inactive version of table TAB is activated in the ABAP Dictionary. The table is created in the database with its new structure and with the name QCM8TAB. The primary index on the table is also created in the database. The structure of database table QCM8TAB is the same as the structure of the active table in the ABAP Dictionary after this step. The database table, however, still does not contain any data. The table therefore does not exist in the database with its original name during conversion. Programs that access this table cannot be executed. You should always make sure that no applications access the table to be converted during conversion.

© SAP AG TAW12 7-8

SAP AG 2002

Conversion Process 4

Data is loaded back into QCM8TAB

44

QCMTAB

Field 1NUMC, 6

Field 2CHAR, 8

Field 3CHAR, 60

000100001200003000

1111A000222B100030B20

Text1...Text2 ...Text3 ...

Field 1NUMC, 6

Field 2CHAR, 8

Field 3CHAR, 30

000100001200003000

1111A000222B100030B20

Text1...Text2 ...Text3 ...

QCM8TAB

Active version of TAB

Field 2CHAR, 8

Field 3CHAR, 30

Field 1NUMC,6

TAB locked

TAB ~ 0

Step 4: The data is loaded back from table QCMTAB to table QCM8TAB (with MOVE-CORRESPONDING). The data is in both tables after this step. When you reduce the size of fields, for example, the extra places are truncated when you reload the data. � Since the data is in both tables QCM8TAB and QCMTAB during the conversion, there are

greater storage requirements during conversion. You should therefore check whether there is sufficient space available in the corresponding tablespace before converting large tables. � There is a database commit after 16 MB when you copy the data from table QCMTAB to table

QCM8TAB. A conversion process therefore needs 16 MB resources in the rollback segment. The existing database lock is released with the Commit and then requested again before the next data area to be converted is edited. � When you reduce the size of keys, only one record can be reloaded if there are several records

whose key cannot be distinguished. It is not possible to say which record this will be. In such a case, you should clean up the data of the table before converting.

© SAP AG TAW12 7-9

SAP AG 2002

Conversion Process 5

Delete lock

77

Delete table QCMTAB

Field 1NUMC, 6

Field 2CHAR, 8

Field 3CHAR, 60

000100001200003000

1111A000222B100030B20

Text1...Text2 ...Text3 ...

QCMTAB

55Field 1

NUMC, 6Field 2

CHAR, 8Field 3

CHAR, 30

000100001200003000

1111A000222B100030B20

Text1...Text2 ...Text3 ...

TAB ~ 0

TAB ~ A11

QCM8 TAB

Rename table and create indexes

66

Active version of TAB

Field 2CHAR, 8

Field 1NUMC,6

Field 3CHAR, 30

TAB locked

Step 5: Table QCMTAB is deleted. Step 6: Table QCM8TAB is renamed to TAB. The secondary indexes defined in the ABAP Dictionary for the table are created again. The views on the table deleted in the first step of the conversion are also created again in the database. Step 7: The lock set at the beginning of the conversion is deleted.

? If the conversion terminates, the table remains locked and a restart log is written. ? Caution: The table does not exist in the database with its original name during conversion.

Programs may not access the table during conversion. Conversions should not run during production! You must at least deactivate all the applications that use the tables to be converted.

? You must clean up terminated conversions. Programs that access the table will otherwise not run correctly. In this case, you must find out why the conversion terminated (for example, overflow of the corresponding tablespace) and correct it. Then continue the terminated conversion.

© SAP AG TAW12 7-10

SAP AG 2002

Possible Problems during Conversions

Tablespace overflow

Data loss if key is reduced in size

Invalid change of type

n Since the data exists in both the original table and temporary table during conversion, the storage requirements increase during conversion. If the tablespace overflows when you reload the data from the temporary table, the conversion will terminate. In this case, you must extend the tablespace and start the conversion in the database utility again.

n If you shorten the key of a table (for example, when you remove or shorten the field length of key fields), you cannot distinguish between the new keys of existing records of the table. When you reload the data from the temporary table, only one of these records can be loaded back into the table. It is not possible to say which record this will be. If you want to copy certain records, you have to clean up the table before the conversion.

n During a conversion, the data is copied back to the database table from the temporary table with the ABAP statement MOVE-CORRESPONDING. Therefore, only those type changes that can be executed with MOVE-CORRESPONDING are allowed. All other type changes cause the conversion to be terminated when the data is loaded back into the original table. In this case, you have to recreate the old state prior to conversion. Using database tools, you have to delete the table, rename the QCM table to its old name, reconstruct the runtime object (in the database utility), set the table structure in the Dictionary back to its old state, and then activate the table.

© SAP AG TAW12 7-11

SAP AG 2002

Resuming Terminated Conversions

What you should do

Syslog

Object log

Dumps

What you should not do

n If a conversion terminates, the lock entry for the table set in the first step is retained. The table can no longer be edited with the maintenance tools of the ABAP Dictionary (Transaction SE11).

n A terminated conversion can be analyzed with the database utility (Transaction SE14) and then resumed. The database utility provides an analysis tool with which you can find the cause of the error and the current state of all the tables involved in the conversion.

n You can usually find the precise reason for termination in the object log. If the object log does not provide any information about the cause of the error, you have to analyze the syslog or the short dumps.

n If there is a terminated conversion, two options are displayed as pushbuttons in the database utility: � After correcting the error, you can resume the conversion where it terminated with the Continue

adjustment option. � There is also the Unlock table option. This option only deletes the existing lock entry for the table

. You should never choose Unlock table for a terminated conversion if the data only exists in the temporary table, for example, if the conversion terminated in steps 3 or 4.

© SAP AG TAW12 7-12

SAP AG 2002

Append Structures 1

Field 1 Field 2 Field 3 Field A Field B

Table

Field 2 Field 3Field 1

Append structure

Field A Field B

n Append structures permit you to append customer fields to a SAP standard table without having to modify the table definition.

n An append structure is a structure that is assigned to exactly one table. There can be several append structures for a table.

n When a table is activated, all the active append structures for the table are found and their fields are appended to the table. If an append structure is created or changed, the table to which it is assigned is also activated and the changes also take effect there when it is activated.

n Like all structures, an append structure defines a type that can be used in ABAP programs. n With Release 4.6C, you can define foreign keys for fields that already exist in the table using an

append structure. Search helps can also be attached to fields that already exist in the table.

© SAP AG TAW12 7-13

SAP AG 2002

Append Structures 2

New SAP version is imported

Field 1 Field 2 Field 3 Field A Field B

Append structure

Field A Field B

Table

Field 2 Field 3Field 1

Field 2 Field 3Field 1 Field 4

n Customers create append structures in their namespace. The append structures are thus protected against overwriting during an upgrade.

n The new versions of the standard tables are imported during the upgrade. When the standard tables are activated, the fields contained in the active append structures are appended to the new standard tables. When append structures are added to a table, you do not have to manually adjust the customer modifications to the new SAP version of the table (Transaction SPDD) during the upgrade.

n The order of the fields in the ABAP Dictionary can differ from the order of the fields in the database. You do not have to convert the table when you add an append structure or insert fields in an existing append structure. The new fields are simply appended to the table in the database. You can always adjust the structure by adjusting the database catalog (ALTER TABLE).

© SAP AG TAW12 7-14

SAP AG 2002

Append Structures 3

Append the fieldon the database

Table

Activate

Field 1 Field 2 Field 3 Field A Field B Field 4

Append structure

Field A Field B

Field 2 Field 3Field 1 Field 4

n The new version of the SAP standard table is activated and the new field is appended to the database table.

n Please note the following points about append structures: � No append structures may be created for pooled and cluster tables. � If a long field (data type LCHR or LRAW) occurs in a table, it cannot be extended with append

structures because such long fields must always be in the last position of the field list (for example, they must be the last field of the table). � If you as a customer add an append structure to an SAP table, the fields in this append structure

should be in the customer namespace for fields, that is they should begin with YY or ZZ. This prevents name collisions with new fields inserted in the standard table by SAP. � If you as a partner have your own reserved namespace for your developments, the fields you select

in append structures should always lie in this namespace.

© SAP AG TAW12 7-15

SAP AG 2002

Summary

l The runtime object and database definition of a table must always be consistent. For this reason, the corresponding database table must be adjusted when you change a table in the ABAP Dictionary.

l The system always tries to make structure changes to tables by changing the database catalog (ALTER TABLE). If this is not possible, a conversion takes place.

l In a conversion, the data is stored in a temporary table and then copied back to the table with its new structure.

l Customer fields should always be added to SAP standard tables using append structures.

© SAP AG TAW12 7-16

Changes to Database Tables Exercises

Unit: Changes to Database Tables

At the conclusion of these exercises, you will be able to:

• Make changes to existing objects

• Convert tables

• Enhance standard tables with append structures without modifying them

The original design of employee management is no longer appropriate after some organizational changes at the airlines. It is therefore necessary to make small changes to objects already created in previous exercises. These changes will be made in this exercise.

1-1 The design of table ZFLCREW## is no longer appropriate. The field for the role of the employee during the flight is too long. Correct this error by reducing the field length to 15 places.

Create a new data element ZROLE## and replace the existing data element with the new one. When you define data element ZROLE##, do not use a domain; instead, enter the data type and length directly when you define the data element. Activate the table.

1-2 The employees with management or maintenance functions have their workplace at an airport. Record information about how to reach these employees in table ZEMPLOY##: a telephone number for reaching maintenance employees at the airport and an office location or where the administrative employees work.

Create an append structure for table ZEMPLOY## containing the following information:

Field Data element

ZZAirport S_AIRPORT

ZZOffice S_BUREAUNO

ZZTelephone S_TELNO

Note: the field names in an append structure must lie in the customer namespace for fields. The field names should therefore begin with ZZ or YY.

© SAP AG TAW12 7-17

1-3 Create a suitable foreign key for field ZZAirport of the append structure.

The table of all airports is called SAIRPORT.

For a complete definition of the foreign key, you must also verify a field of the appending table (ZEMPLOY##).

Start Program BC430_CHECK with Transaction SE38 after this exercise. The program checks whether your solutions are correct.

© SAP AG TAW12 7-18

Changes to Database Tables Solutions

Unit: Changes to Database Tables

1-1 Go to change mode in the maintenance screen for table ZFLCREW##. Take the following steps.

1) Overwrite data element SEMP_ROLE in column Field type with the name of your data element ZROLE##. Save the change.

2) Select the name ZROLE##. In the next dialog box, confirm that you want to create the data element.

3) The maintenance screen for data elements appears. Enter a short text.

4) Select tab page Definition. Choose Built-in type. You can now enter values for fields Datatype, Length, and Decplaces. Enter CHAR as data type and 15 as length.

5) On tab page Field label, maintain the text for the data element.

6) Activate the data element.

7) Goto the activation log. You are reminded that shortening the field requires a conversion of table ZFLCREW##.

8) Go back to the table maintenance screen.

9) Navigate to the database utility with Utilities → Database utility.

10) Choose Activate and adjust database. Confirm the next security query. The system converts the table.

1-2 To define the append structure for table ZEMPLOY##:

1) Go to display mode in the maintenance screen for table ZEMPLOY##.

2) Choose Goto → Append structure.

3) In the next dialog box, enter the required name for the append structure. It must satisfy the usual naming conventions. Choose Continue.

4) The maintenance screen for the append structure is displayed. Maintenance of the append structure is analogous to that for a structure.

5) Enter a short text and insert fields ZZAirport, ZZOffice, and ZZTelephone with the specified data elements.

6) Note: all the fields of an append structure must lie in the customer namespace. The field names therefore must begin with ZZ or YY.

7) Activate the append structure. Display the activation log with Utilities→ Activation log.

© SAP AG TAW12 7-19

Table ZEMPLOY## automatically adjusted when you activate the append structure. The new fields are appended to the existing fields in the database.

1-3 The foreign key must be defined in the append structure maintenance routine. You can go there either by entering its name as data type in the initial screen of the ABAP Dictionary and choosing Change or with Goto→ Append structure in the maintenance screen for table ZEMPLOY##. Take the following steps:

1) Place the cursor on field Airport. Choose the key icon. Copy the system proposal.

2) The maintenance screen for the foreign key appears. The check table and the field assignments are already filled due to the system proposal. Enter a suitable Short description.

3) The foreign key cannot be fully specified using just the append structure since the key of check table SAIRPORT contains both a client field and an airport code, while the append structure has no client field. You should verify that the client field is supplied from the append table ZEMPLOY##.

4) Choose Non-key-fields / candidates as the type of foreign key fields (since the Airport field is not a key field of table ZEMPLOY##) and as cardinality C (since not every employee is assigned to an airport) to CN (since several employees can be assigned to the same airport).

5) Choose Copy and activate the append structure.

© SAP AG TAW12 8-1

SAP AG 2002

l Why do you need views?

l Creating a view by join, projection, and selection

l Join conditions and foreign keys

l Selection of data with views

l Database views

l Maintenance views

l Inner and outer joins

Views

© SAP AG TAW12 8-2

SAP AG 2002

Course Objectives

At the end of this unit, you will be able to:

l Judge how a view is created from tables with join, projection, and selection

l Create database views

l Set up a link between foreign keys and join conditions

l Use views in programs for data selection

l Judge when to use maintenance views

l Recognize the difference between an inner join and an outer join

© SAP AG TAW12 8-3

SAP AG 1999

F3F2F1F4 F5

F6 F7 F8

Table 3Table 2

Table 1

View on the tables

View on data that is distributed on more than one table

Why do you Need Views?

F1 F2 F3 F5 F8

n Data for an application object is often distributed on several database tables. Database systems therefore provide you with a way of defining application-specific views on data in several tables. These are called views.

n Data from several tables can be combined in a meaningful way using a view (join). You can also hide information that is of no interest to you (projection) or only display those data records that satisfy certain conditions (selection).

n The data of a view can be displayed exactly like the data of a table in the extended table maintenance.

© SAP AG TAW12 8-4

SAP AG 2002

Table TABA

Table TABB

1 11222

Text 1 Text 3Text 4Text 5

Text 2

Text 6

A

AB

B

Field 1 Field 2 Field 3 Field 4 Field 5

Field 1 Field 2 Field 3 Field 4 Field 5

1 Text 11 Text 11 Text 11 Text 12 Text 22 Text 22 Text 22 Text 2

1122

Text 3Text 4Text 5Text 6

A

AB

B1122

Text 3Text 4Text 5Text 6

A

AB

B

Cross-product of tables TABA and TABB

Structure of a View - Starting Situation

n The structure of a view and selection of the data using this view will be shown with an example. n Given two tables TABA and TABB. Table TABA contains two entries and table TABB 4 entries. n The tables are first appended to one another. This results in the cross-product of the two tables, in

which each record of TABA is combined with each record of TABB.

© SAP AG TAW12 8-5

SAP AG 1999

Join condition: TABA - Field 1 = TABB - Field 3

Field 1 Field 2 Field 3 Field 4 Field 5

1 Text 11 Text 11 Text 11 Text 12 Text 22 Text 22 Text 22 Text 2

1122

Text 3Text 4Text 5Text 6

A

AB

B1122

Text 3Text 4Text 5Text 6

A

AB

B

Reduction of the cross-product

Structure of a View - Join Condition

n Usually the entire cross-product is not a meaningful selection. You should therefore limit the cross-product with a join condition. The join condition describes how the records of the two tables are related.

n In our example, Field 3 of TABB identifies Field 1 of TABA. The join condition is then: TABA - Field 1 = TABB - Field 3

n With this join condition, all the records whose entry in Field 1 is not identical to the entry in Field 3 are removed from the cross product. The column for Field 3 in the view is therefore unnecessary.

© SAP AG TAW12 8-6

SAP AG 1999

Field 1 Field 2 Field 4 Field 5

1 Text 11 Text 12 Text 22 Text 2

Text 3Text 4

AB

Text 5Text 6

AB

Field 1 Field 2 Field 5

1 Text 11 Text 12 Text 22 Text 2

Text 3Text 4Text 5Text 6

Projection

Structure of a View - Field Selection (Projection)

n Often some of the fields of the tables involved in a view are of no interest. You can explicitly define the set of fields to be included in the view (projection).

n In our example, Field 4 is of no interest and can therefore be hidden.

© SAP AG TAW12 8-7

SAP AG 2002

Selection condition: TABB - Field 4 = ‘A’.

Field 1 Field 2 Field 5

1 Text 11 Text 12 Text 22 Text 2

Text 3Text 4Text 5Text 6

Field 1 Field 2 Field 5

1 Text 11 Text 12 Text 22 Text 2

Text 3Text 4Text 5Text 6

Structure of a View - Selection Condition

Field 4

ABAB

n The set of records that can be displayed with the view can be further restricted with a selection condition.

n In our example, only those records with value A in Field 4 should be displayed with the view. n A selection condition therefore can also be formulated with a field that is not contained in the view.

© SAP AG TAW12 8-8

SAP AG 2002

MANDT CARRID CONNID FLDATE BOOKID CUSTOMID ... SBOOK

MANDT CARRID CONNID CITYFROM CITYTO SPFLI...... ...

001

001

SCUSTOMMANDT ID CITYNAME ...

122356 Smith New York001 ...

122356

122356

...

...

001

001

New York

TokyoBerlin

BerlinAA

AA

LH

LH

48

324

324

48

...

...

...

...

3689

3690

...

...

...

...

How are Tables Linked to Views?

n Example: Travel agencies sometimes have to check which customer is booked on which flights. The corresponding data is distributed on several tables: : Customer data, such as the customer number, name and address SBOOK: Booking data, such as the carrier, flight number and passenger (customer number)

SPFLI: Flight data, such as the city of departure and city of arrival n You have to create a view on tables SCUSTOM, SBOOK and SPFLI to obtain the booking data. n In this case, the join conditions are:

SBOOK-MANDT = SCUSTOM-MANDT SBOOK-CUSTOMID = SCUSTOM-ID SPFLI-MANDT = SBOOK-MANDT SPFLI-CARRID = SBOOK-CARRID SPFLI-CONNID = SBOOK-CONNID

© SAP AG TAW12 8-9

SAP AG 2002

MANDT ID NAME CITY CARRID CONNID FLDATE BOOKID CITYFROM CITYTO

001

001

122356 Smith New York AA 48 3689 New York Berlin

122356 Smith New York LH 324 3690 Berlin Tokyo

View SCUS_BOOK for customer bookings

Structure of the View

4.9.1999

9.9.1999

n You can get the bookings for a particular customer by selecting the corresponding records for keys MANDT and CUSTOMID in table SBOOK.

n You can get the flight data from table SPFLI for each booking in table SBOOK by selecting the corresponding record for the keys MANDT, CARRID and CONNID from table SPFLI.

n You can display only the customer bookings that were not canceled using the view with the following selection condition:

SBOOK-CANCELED <> X n The join conditions can also be derived from the existing foreign key relationships. Copying the join

conditions from the existing foreign keys is supported in the maintenance transaction. n The field names of the underlying table fields are normally used as field names in the view.

However, you can also choose a different field name. This is necessary for instance if two fields with the same name are to be copied to the view from different tables. In this case, you must choose a different name for one of the two fields in the view.

© SAP AG TAW12 8-10

SAP AG 2002

REPORT SAPBC430_FLIGHTS.

DATA: WA_FLIGHTS TYPE LINE_TYPE_FLIGHTS,ITAB_FLIGHTS TYPE TABLE OF LINE_TYPE_FLIGHTS.

SELECT CARRID CARRNAME CONNID CITYFROM CITYTO FLDATE SEATSMAX SEATSOCC INTO TABLE ITAB_FLIGHTSFROM SV_FLIGHTSWHERE CITYFROM IN SO_CITYFAND CITYTO IN SO_CITYTAND SEATSOCC < SV_FLIGHTS~SEATSMAXORDER BY CARRID CONNID FLDATE.

IF SY-SUBRC <> 0.WRITE: / ‘No bookings exist’.

ENDIF.

Data Selection with Views

n You can also formulate the join condition directly in OPEN SQL. n You would get the same result using an Inner Join: SELECT C~CARRID C~CARRNAME P~CONNID P~CITYFROM P~CITYTO F~FLDATE F~SEATSMAX F~SEATSOCC INTO TABLE ITAB_FLIGHTS FROM ( SCARR AS C INNER JOIN SPFLI AS P ON C~CARRID = P~CARRID ) INNER JOIN SFLIGHT AS F ON F~CARRID = P~CARRID AND F~CONNID = P~CONNID WHERE CITYFROM IN SO_CITYF AND CITYTO IN SO_CITYT AND SEATSOCC < F~SEATSMAX ORDER BY C~CARRID P~CONNID F~FLDATE. n A view has type character and can be accessed in programs like all other types and can be used to

define data objects.

© SAP AG TAW12 8-11

SAP AG 1999

What is displayed with the view?

Inner join Outer join

Table TABA Table TABB

Join condition

Field 1 Field 2 Field 4

A Text 1B Text 2

Text 3Text 4

Field 1 Field 2 Field 4

A Text 1B Text 2

Text 3Text 4

C Text 5

AB

Text 1Text 2

Field 1 Field 2

C Text 5

AB

Text 3Text 4

Field 3 Field 4

Inner and Outer Joins

n The set of data that can be selected with a view greatly depends on whether the view implements an inner join or an outer join.

n With an inner join, you only get those records which have an entry in all the tables included in the view. With an outer join, on the other hand, those records that do not have a corresponding entry in some of the tables included in the view are also selected.

n The hit list found with an inner join can therefore be a subset of the hit list found with an outer join. n Database views implement an inner join. You only get those records which have an entry in all the

tables included in the view. n Maintenance views implement an outer join.

© SAP AG TAW12 8-12

SAP AG 1999

F6 F7 F8

Table 3

F4 F5

Table 2

F3F2F1

Table 1

View definition in the ABAP Dictionary

View definition in the database

Is created in the DBduring activation

ABAP program

F1 F2 F3 F5 F8

F1 F2 F3 F5 F8

Database Views

Database interface

n A database view is defined in the ABAP Dictionary and automatically created on the database during activation. Accesses to a database view are passed directly to the database from the database interface. The database software performs the data selection.

n If the definition of a database view is changed in the ABAP Dictionary, the view created on the database must be adjusted to this change. Since a view does not contain any data, this adjustment is made by deleting the old view definition and creating the view again in the ABAP Dictionary with its new definition.

n The maintenance status defines whether you can only read with the view or whether you can also write with it. If a database view was defined with more than one table, this view must be read only.

n The data read with a database view can be buffered. View data is buffered analogously to tables. The technical settings of a database view control whether the view data may be buffered and how this should be done. The same settings (buffering types) can be used here as for table buffering. The buffered view data is invalidated when the data in one of the base tables of the view changes.

© SAP AG TAW12 8-13

SAP AG 2002

Includes in Database Views

F 8F 7

TABB TABB included in included in

viewview

Database view on TABA, TABB and TABC

TABBTABA TABC

F 1 F 3 F 4 F 5 F 6F 4 F 5 F 6 F 8

F 2 F 3F 1 F 5 F 6F 4

n You can include entire tables in database views. In this case, all the fields of the included table become fields of the view (whereby you can explicitly exclude certain fields). If new fields are included in the table or existing fields are deleted, the view is automatically adjusted to this change. A new or deleted field is therefore automatically included in the view or deleted from it.

n If an append structure is added to a table included in a view, the fields added with the append structure are automatically included in the view.

n To include a table in a view, you must enter an asterisk (*) in field View field in the view maintenance, enter the name of the table to be included in the field Table, and enter * again in the field Field name.

n If you do not want to insert a field of the included table in the view, you must enter a hyphen (-) in field View field, the name of the included table in field Table, and the name of the field to be excluded in field Field name.

n As of Release 4.6C, fields of the base tables of a database view can be included in the view without modifications using an append view. This is analogous to enhancing a table using an append structure. An append view is assigned to exactly one database view. But more than one append view can be created for a database view.

© SAP AG TAW12 8-14

SAP AG 1999

F6 F7 F8Table 3

F3F2F1Table 1

Table 2F4 F5

Maintenance view on the tables Data exchange with

the maintenance view

Foreign key Foreign key

F1 F2 F3 F5 F8

Maintenance Views

Application object

n Data that is distributed on more than one table often forms a logical unit, called an application object. You should be able to display, change and create the data of such an application object together. Users usually are not interested in the technical implementation of the application object, such as the distribution of the data on several tables.

n You can maintain complex application objects in a simple way using a maintenance view. The data is automatically distributed on the underlying database tables.

n All the tables used in a maintenance view must be linked with a foreign key. This means that the join conditions are always derived from the foreign key in the maintenance view. You cannot enter the join conditions directly as in a database view.

n A maintenance interface with which the data of the view can be displayed, changed and created must be generated from the definition of a maintenance view in the ABAP Dictionary.

n When the maintenance interface is created, function modules that distribute the data maintained with the view on the underlying tables are automatically generated.

n The maintenance interface is generated with the Transaction Generate Table View (Transaction SE54) or from the view maintenance screen with Utilities -> Tab.maint.generator.

© SAP AG TAW12 8-15

SAP AG 2002

Unit Summary

l Data records that are distributed on different tables can be combined using a view.

l A view is derived from the tables involved using the relational operators join, projection, and selection.

l ABAP programs can select data using a view. Selection with a database view is usually faster than direct table selection with a nested SELECT statement.

l You can maintain data records from several tables together using a maintenance view.

© SAP AG TAW12 8-16

Exercises

Unit: Views

At the conclusion of these exercises, you will be able to:

• Create views

• Define join conditions

• Buffer database views

The data existing for an employee is distributed on several tables (corresponding to the relational data model). For some exercises, however, a complete view on this data is needed. In this exercise, the corresponding views are implemented by creating views.

1-1 The flight personnel (all pilots and stewards) must be selected when a flight crew is set up. Not all the data in table ZEMPLOY## may be displayed when this data is accessed; for example, the employee setting up the teams may not see the salary of the crew members. The telephone number of the employee's department should be output in case of questions.

1-1-1 Create a suitable database view ZEMPFLY## that satisfies these requirements. The following information about an employee should be displayed:

Client

Carrier

Personnel number

First name

Last name

Telephone number of the department

Department code

1-1-2 Make sure that only flight personnel can be selected with the view.

1-1-3 You probably will have to (frequently) access the data using the view. The selected data should therefore be buffered in order to increase performance. Choose full buffering as buffering type.

© SAP AG TAW12 8-17

1-2 Supplementary Exercise: Create a maintenance view with the name ZPARTNER##, with which you can easily maintain new business partners. The business partners are entered in table SBUSPART. A business partner can be either a flight customer or a travel agency. If it is a travel agency, there will be a corresponding entry in table STRAVELAG.

The view should also permit you to maintain tables SBUSPART and STRAVELAG at one time. Include all the necessary fields of the tables in the view.

Generate the maintenance interface. Use the following parameters:

Function group: ZZBC430##

Authorization group: SUNI

Maintenance type: one-step

Overview screen: 100

Maintain the data of a new travel agency using the enhanced table maintenance (System → Services → Table maintenance → Ext. table maint.).

© SAP AG TAW12 8-18

Solutions

Unit: Views

1-1 The view should permit a view on data in tables ZEMPLOY## and ZDEPMENT##. To create the view:

1) In the initial screen of the ABAP Dictionary, mark object type View, enter the object name ZEMPFLY## and choose Create.

2) A dialog box appears in which you should select the view type. Mark Database view and choose Copy.

3) Enter a short text in the next screen.

The view should display data about employees (from table ZEMPLOY##) and departments (from table ZDEPMENT##).

4) First enter table ZEMPLOY## in field Tables.

5) Choose Relationships. All the foreign key relationships of table ZEMPLOY## to other tables are listed. Mark the relationship to table ZDEPMENT## and choose Copy.

6) The join conditions are copied from the foreign key. In a different mode, display the foreign key between the two tables and notice the relationship between the foreign key and the join conditions.

7) You now have to copy fields from the tables to the view. Select View fields.

8) Choose Table fields. In the next dialog box, mark table ZEMPLOY## and select Choose.

9) All the fields of table ZEMPLOY## are listed. Mark fields Client, Carrier, Personnel number, First name, and Last name. Choose Copy. The fields are now inserted in the view.

10) Again choose Table fields. In the dialog box, choose table ZDEPMENT## and insert fields Department telephone and Department code in the view as described above.

Only flight personnel should be selected with the view. You can define this restriction with a selection condition.

11) Choose Selection conditions.

12) The restriction whether an employee belongs to the flight personnel is contained in field ZEMPLOY##-Area. Enter it in columns Table and Field name.

13) Flight personnel are identified by the value F in field Area. Enter EQ in the column Operator and ’F’ (including the single quotes)in column Compar. value.

You now have to buffer the view.

© SAP AG TAW12 8-19

14) Choose Goto → Technical settings. The maintenance screen for the technical settings of the view appears. With the exception of some attributes that are meaningless for views and which are therefore not displayed, the screen is analogous to the corresponding maintenance screen for tables.

15) Mark Buffering switched on and Fully buffered.

16) Save the technical settings and return to the view maintenance screen.

17) Activate the view.

1-2 Proceed as follows:

1) In the initial screen of the ABAP Dictionary, mark object type View, enter the object name ZPARTNER## and choose Create.

2) A dialog box appears in which you should select the view type. Mark Maintenance view and choose Copy.

3) Enter a short text in the next screen.

You want to maintain the data in tables SBUSPART and STRAVELAG together in the maintenance view. If you wanted to enter a new partner directly, you would first have to enter it in table SBUSPART. Only then could you enter the corresponding data in table STRAVELAG (because of the existing foreign key check between SBUSPART and STRAVELAG). You therefore first have to include table SBUSPART in the definition of the maintenance view.

4) Enter table SBUSPART in the field Tables. The key fields of this table are automatically included in the view as fields.

5) Place the cursor in field Tables on entry SBUSPART. Choose Relationships.

6) A dialog box appears listing all existing foreign key relationships of table SBUSPART to other tables. Mark the foreign key relationship to table STRAVELAG and choose Copy.

7) The join conditions are created from the foreign key. The join conditions have the following form:

SBUSPART-MANDANT = STRAVELAG-MANDT

SBUSPART-BUSPARTNUM = STRAVELAG-AGENCYNUM

8) You now have to include the fields of both tables in the view. Go to tab page View fields. Position the cursor on table SBUSPART and choose Table fields. A list of all the fields of the table appears. Choose Select all and then Copy.

9) Include all the fields of table STRAVELAG with the exception of fields MANDT and AGENCYNUM in the view in the same way. These fields are linked to the corresponding fields of table SBUSPART with the join conditions and therefore should not appear in the view.

10) Activate the view.

Now generate a maintenance interface for the view.

11) Choose Utilities → Table maintenance generator.

12) Enter authorization group SUNI and function group ZZBC430## in the next screen.

© SAP AG TAW12 8-20

13) Mark maintenance type one-step. Select number 0100 as maintenance screen number of the overview screen.

14) Choose Create. The development class of the function group and the generated maintenance objects are prompted. In both cases, choose Local object.

15) Call the extended table maintenance with the given menu path and enter the data of a new travel agency. With the Data Browser (in the menu environment of the initial screen of the ABAP Dictionary), verify that the data of the new travel agency was written in tables SBUSPART and STRAVELAG.

© SAP AG TAW12 9-1

SAP AG 1999

l Input help in the R/3 System

l ABAP Dictionary object search help

n Selection method of a search help

n Dialog behavior of a search help

n Interface of a search help

l Attaching search helps to fields

l Collective search helps and elementary search helps

l Append search helps

Search Helps

© SAP AG TAW12 9-2

SAP AG 2002

Course Objectives

At the end of this unit, you will be able to:

l Define an input help process with a search help

l Define a search help with several alternative search paths

l Use the different mechanisms for the search help attachment to assign a search help to a screen field

l Determine whether a screen field has an input help and determine its form

l Enhance a collective search help using an append search help without modifications

© SAP AG TAW12 9-3

SAP AG 2002

SAP R/3 Standard Function: Input Help

Carrier

Flight number

. . .

Maintenance of flights

LH

No.

Depart. city Arrival city

Carrier

0400 Frankfurt New York

0402 Frankfurt New York

LH

2402 Frankfurt Berlin

... ... ...

F4

n The input help (F4 help) is a standard function of the R/3 System that permits the user to display a list of possible values for a screen field. A value can be directly copied to an input field by list selection.

n The fields having an input help are shown in the R/3 System by the input help key to the right of the field. This key appears as soon as the cursor is positioned on the corresponding screen field. The help can be started either by selecting on this screen element or with function key F4.

n If the number of possible entries for a field is very large, you can limit the set of displayed values by entering further restrictions.

n The display of the possible entries is enhanced with further useful information about the displayed values. This feature is especially useful if the field requires the entry of a formal key.

n Since the input help is a standard function, it should look and behave the same throughout the entire R/3 System. The development environment therefore provides tools for assigning a standardized input help to a screen field.

n The precise description of the input help for a field is usually defined by its semantics. For this reason, the input help for a field is normally defined in the ABAP Dictionary.

© SAP AG TAW12 9-4

SAP AG 2002

Requirements of the Input Help

Determinethe values

Dialog withthe user

Take context into consideration Return values

n A number of requirements must be met for the input help of a screen field (search field): � Information (about the context) known to the system must be taken into consideration in the input

help. This includes entries the user already made in the current input template as well as information obtained in previous dialog steps. Normally the input help uses the context to limit the set of possible values. � The input help must determine the values that can be offered to the user for selection. The data to

be displayed as supplementary information in the list of possible values must also be determined. When the possible values are determined, the restrictions resulting from the context and from further search conditions specified by the user must also be taken into consideration. � The input help must hold a dialog with the user. This dialog always contains the presentation of

the possible values (with supplementary information) in list form and the possibility to select a value from this list. A search template in which the user can define conditions for the values to be displayed is also sometimes required . � If the user selects a value, the input help must return the value to the search field. The input

template often contains more fields (often only display fields) containing further explanatory information about the search field. The input help should also update the contents of these fields in this case.

© SAP AG TAW12 9-5

SAP AG 2002

ABAP Dictionary Object Search Help

Search help

Selectionmethod

Dialog behavior

Interface

n The ABAP Dictionary object search help is used to describe an input help. The definition of a search help contains the information the system needs to satisfy the described requirements.

n The interface of the search help controls the data transfer from the input template to the F4 help and back. The interface defines the context data to be used and the data to be returned to the input template when a value is selected.

n The internal behavior of the search help describes the F4 process itself. This includes the selection method with which the values to be displayed should be determined as well as the dialog behavior describing the interaction with the user.

n As with a function module, search helps distinguish between the interface with which it exchanges data with other software components and the internal behavior (for function modules, the latter is defined by the source text).

n It only makes sense to define a search help if there is a mechanism available with which the search help can be accessed from a screen. This mechanism, called the search help attachment, will be described later.

n Like the editor for function modules, the editor for search helps also enables you to test an object. You can thus test the behavior of a search help without assigning it to a screen field.

© SAP AG TAW12 9-6

SAP AG 2002

SPFLI

SELECT * FROM SPFLIWHERE CARRIER = 'LH'.

Selection Method of a Search Help

Carrier

Flight number

. . .

Maintenance of flights

LH

F4

n The possible values displayed for a field by the input help are determined at runtime by a selection from the database. When a search help is defined, you must define the database object from which the data should be selected by specifying a table or a view as the selection method.

n It makes sense to use a view as selection method if the data about the possible values that is relevant for the input help is distributed on several tables. If this data is all in one table or in the corresponding text table, you can use the table as a selection method. The system automatically ensures that the text of the text table is used in the user's logon language.

n If there is not yet a view that combines the data that is relevant for an input help, you must first create it in the ABAP Dictionary.

n Maintenance views may not be used as the selection method for search helps. Normally a database view is used. However, you should note that database views (in the R/3 System) are always created with an inner join. As a result, only those values having an entry in each of the tables involved are offered in the input help. Sometimes the values should be determined with an outer join. In this case you should choose a help view as the selection method. You can find more information about help views in the appendix.

n If the selection method of a search help is client-dependent, the possible values are only selected in the user's logon client.

© SAP AG TAW12 9-7

SAP AG 1999

Carrier

Connection number

Departure city

Arrival city

Limit display to 500

0*LH

No limit

Description of the Dialog Behavior

No.

Depart. city Arrival city

Carrier

0400 Frankfurt New York

0402 Frankfurt New York

LH

2402 Frankfurt Berlin

... ... ...

F4

=

[*]

n The possible values are presented in the dialog box for displaying the hit list and the user can select values from here. If the possible values are formal keys, further information should also be displayed.

n If the hit list is very large, the user should be able to define further restrictions for the attributes of the entry. Restricting the set of data in this way both increases the clarity of the list and reduces the system load. Additional conditions can be entered in a further dialog window, the dialog box for restricting values.

n The dialog type of a search help defines whether the dialog box for restricting values should be displayed before determining the hit list.

n You must define the characteristics to appear on either (or both) of the dialog boxes as parameters in the search help. You can use all the fields of the selection method (with the exception of the client field) and the non-key fields of your text table as parameters.

n You define which parameter should appear in which dialog box (in what order) by assigning the parameters positions in the two dialog boxes. You can thus use different parameters (or different orders) in the two dialog boxes.

n Types must be defined for search help parameters with data elements. These define the display in the two dialog boxes. If nothing else is defined, a parameter uses the data element of the corresponding field of the selection method.

© SAP AG TAW12 9-8

SAP AG 2002

Interface of a Search Help

No.

Depart. city Arrival city

Carrier

0400 Frankfurt New York

0402 Frankfurt New York

LH

Carrier

Flight number

. . .

0*

LH

Import and export

Export

F4

F4

n When you define a parameter of a search help, you must also define whether it should be used to copy data to the input help (IMPORT parameter) or whether to return data from the input help (EXPORT parameter).

n The IMPORT and EXPORT parameters of a search help together make up your interface. (This is also analogous to function modules.)

n You can also define interface parameters that do not appear in either the dialog box for displaying the hit list or the dialog box for restricting values. This is useful for example when screen fields that do not appear on either of the two dialog boxes are to be updated when you select a value.

n The location from which the IMPORT parameters of a search help get their values and the screen fields in which the contents of the EXPORT parameters of the search help are returned are defined in the search help attachment.

n The search field is a special case. Its contents are only used in the input help if it is a search string (that is, if it contains a * or a +) and the parameter linked with the search field is an IMPORT parameter.

n Parameters that only contain additional information about the search field should not be defined as IMPORT parameters since the user must otherwise empty the corresponding screen fields each time before he can define a new value with the input help.

© SAP AG TAW12 9-9

SAP AG 2002

How do you Use Search Helps?

Search field

Field 1

Input template

Field 3

Table/structure

Field 1 Field 3Search field ...

Definitions in theScreen Painter

Linkin DDIC

Internal behavior

Interface

F4

Search help

n A search help describes the flow of an input help. The search help can only take effect using a mechanism that assigns the search help to this field. This mechanism is called the search help attachment to the field.

n Attaching a search help to a field has an effect on the field's behavior. It is therefore considered to be part of the field definition.

n The semantic and technical attributes of a screen field (type, length, F1 help, ...) are not normally defined directly when the input template is defined. On the contrary, only a reference to an ABAP Dictionary field (usually with the same name) is specified in the Screen Painter. The screen field takes on the attributes of this field from the ABAP Dictionary. The same principle is also used to define the input help of a screen field. The search help is thus attached to the ABAP Dictionary search field and not to the screen field.

n In the search help attachment, the interface parameters of the search help and the screen fields providing data for the input help or getting data from the input help are assigned to one another. The search field must be assigned to an EXPORT parameter of the search help at this time. This parameter should also be an IMPORT parameter so that the user can take advantage of search patterns that are already entered.

n Fields that do not have a search help attachment can also have an input help since further mechanisms (for example, domain fixed values) are also used for the F4 help.

© SAP AG TAW12 9-10

SAP AG 2002

Search Help Attachment in the ABAP Dictionary

Table/structure

MANDT Field 1 Field 3Search field ...

Search help

Check table

MANDT Key1 Key 2 Data part

Internal behavior

Interface

Data element

n There are three mechanisms for attaching a search help to a field of the ABAP Dictionary: 1. A search help can be attached directly to a field of a structure or table. The definition of this

attachment is analogous to that of a foreign key. You have to define an assignment (between the interface parameters of the search help and the fields of the structure) for which the system makes a proposal.

2. If a field has a check table, its contents are automatically offered as possible values in the input help. The key fields of the check table are displayed. If a check table has a text table, its first character-like non-key field is displayed. If you are not satisfied with the described standard display of the data of the check table, you can attach a search help to the check table. This search help is used for all the fields that have this table as check table. You have to define an assignment between the interface of the search help and the key of the check table when you define the attachment.

3. The semantics of a field and its possible values are defined by its data element. You can therefore attach a search help to a data element. The search help is then available for all the fields that refer to this data element. In the attachment you must define an EXPORT parameter of the search help for the data transfer.

n Attaching a search help to a check table (or a data element) can result in a high degree of reusability. However, there are restrictions on passing further values via the interface of the search help.

© SAP AG TAW12 9-11

SAP AG 2002

Overview: Mechanisms for the Input Help

does not exist

exists

PROCESS ON VALUE-REQUEST

Input help from screen

Check of theflow logic

Search help forscreen field

Search help for field

Search help fordata element

Search help for check table

Fixed values

Time or calendar help

Check table withtext table

Key values of check table

Check table help

n In order to offer a meaningful input help for as many screen fields as possible, the R/3 System uses a number of mechanisms. If there is more than one such mechanism available for a field, the one that is furthest left or at the top of the above hierarchy is used.

n In addition to the options described above for defining the input help of a field in the ABAP Dictionary, you can also define it in the screen field. The disadvantage, however, is that there is no automatic reuse.

n With the screen event POV, you can program the input help of a field by yourself. You can adjust the design of the help to the standard help using the function modules F4IF_FIELD_VALUE_REQUEST or F4IF_INT_TABLE_VALUE_REQUEST. However, you should check to see if the part of the input help that you programmed yourself should be implemented as a search help exit instead (see Appendix).

n You can also attach a search help to a screen field in the Screen Painter. There are some functional restrictions on this kind of attachment as compared with attachment in the Dictionary.

n You should no longer use the input checks defined directly in the flow logic of the screen, from which it is also possible to derive input helps.

n The function Technical info is offered in the hit list in the menu of the right mouse key. It can be used to find out which of the specified mechanisms is being used.

© SAP AG TAW12 9-12

SAP AG 1999

Performance of the Input Help

Carrier

Flight number

. . .

Maintenance of flights

LH

F4

n You sometimes have to search a large amount of data with an input help. This means that you might have to wait a long time for the possible entries to be displayed, and can also result in a significant increase in the load on the system.

n When you define a search help, you should therefore check whether you should take measures to optimize the accessing behavior for the selection method. This is especially true if the selection uses a view and thus more than one physical table.

n If the number of entries in the selection method is very large, you should restrict the hit list with further conditions. This also increases the clarity of the hit list. The additional conditions can directly result from the context, or can be entered in the dialog box for restricting values by the user. The performance of the input help can frequently be significantly improved by creating an index on the fields used to formulate the restrictions.

n If the number of entries in the selection method is relatively small, you should always check whether the selection method can be buffered.

© SAP AG TAW12 9-13

SAP AG 2002

Alternative Search Paths

What was thebooking numberfor my flightto New York?

What bookings were made in our travel agency?

n In the relational data model, entities are usually represented by formal keys. In real life, however, these entities are often identified by one or more of their attributes. For example, the key for a person is the personnel number. A person will generally describe another with his name and possibly his address.

n The attributes used to identify an entity can differ from one user to the next and from situation to situation. A user wants to use these attributes in an input help to define a value for a field that requires that a formal key be entered.

n You therefore need search paths permitting access to the data using non-key fields. Several different search paths should be possible for one field.

n A search path for a field can be implemented with a search help having the form described above. To describe an input help with more than one alternative search path, a set of search helps can be combined into a new object in the R/3 System. Since this object is the description of the input help for a field, it is also called a search help.

n In contrast to the elementary search helps described above, the search helps that combine several search paths are called collective search helps.

n Collective search helps are sometimes used to map the distribution of the possible entries for a field into several (disjunct) datasets.

© SAP AG TAW12 9-14

SAP AG 2002

Collective Search Helps and Elementary Search Helps

Included search helps

Collective search help

Internal behavior

Interface

InterfaceInterface

Internal behavior

n Like an elementary search help, a collective search help has an interface of IMPORT and EXPORT parameters with which it exchanges data. Using this interface, the collective search help can be attached to fields, tables and data elements exactly like an elementary search help. Only one search help can be attached to a field, table or data element. Several search paths are therefore attached with a collective search help.

n You can omit the components for describing the dialog behavior and data selection when you define a collective search help. The included search helps are listed here. You must assign the parameters of the collective search help to the interface parameters of the included search help for each inclusion.

n A search help can also be included in several collective search helps and at the same time itself be attached to fields, tables and data elements. A collective search help can also be included in another collective search help.

n When you use a collective search help, you are offered the elementary search helps contained in the collective search help as parallel tab pages. If you repeatedly use a collective search help, the tab page that was last used is automatically active. This is because most users always use the same search path.

© SAP AG TAW12 9-15

SAP AG 2002

Append Search Helps

Included search helps

. . .

(customer) appendsearch help

Included search helps

. . .

(SAP) collective search helpappends

n The set of search paths that are meaningful for an object greatly depends on the particular circumstances of the SAP customer. The customer often would like to enhance the standard SAP collective search helps with his own elementary search helps. Release 4.6 provides an append technique that permits the enhancement of collective search helps without modifications.

n An append search help is a collective search help that is assigned to another collective search help (its appending object) and that enhances it with the search helps it includes. The append search help uses the interface of its appending objects.

n The append search help lies in the customer namespace. Normally the search helps included in the append search help are also created by the customer and lie in the customer's namespace. However, the required elementary search help might already be provided by SAP, in which case, the customer only has to add it to his own append search help.

n Append search helps are used with SAP to improve component separation. Some SAP collective search helps therefore already have one or more append search helps in the standard search help. Customer enhancements should always be made by creating a separate append search help.

n SAP collective search helps often contain elementary search helps that are not required by all customers. The search helps you do not need can be hidden using an append search help. To do this, the corresponding search help must be included in the append search help and the hidden flag must be set.

© SAP AG TAW12 9-16

SAP AG 1999

l The input help (F4 help) is a standard function of the R/3 System

l Search helps permit an easy and flexible description of input helps

l Tables and views can be used as the selection method of a search help

l The appearance of the input help is controlled by the parameters of the search help

l Search helps can be attached to fields, tables and data elements

l Input helps with alternative search paths are implemented with collective search helps

l With append search helps, search helps for standard collective search helps can be added or hidden without modifications

Unit Summary

© SAP AG TAW12 9-17

Search Helps Exercises

Unit: Search Helps

At the conclusion of these exercises, you will be able to:

• Implement input helps with elementary search helps

• Define input helps with more than one search path using collective search helps

• Add or remove search paths for collective search helps without modifications

Many management tasks require that you search for employee data. Suitable search options are needed to do this. Such search options will be implemented in this exercise.

1-1 Go to the display screen for table ZDEPMENT## and call Utilities → Table contents → Create entries. An input template appears in which you can create new entries for table ZDEPMENT## (for example, new departments). The head of the new department should also be defined here. Make this entry in field Department head. Maintenance of this field should be supported with an input help that displays the (personnel number of the) employee.

Verify that the field already has an input help. Find out which input help mechanism is used here.

The objective is to make the input help for check table ZEMPLOY## more user-friendly. You will check your success later by calling the input help again.

To do this, create an elementary search help ZEMPLOY##_ESH1.

The following attributes should appear in the specified order in the hit list:

Carrier

First name

Last name

Personnel number

Because of the large number of employees, you should restrict the displayed values by specifying the first and/or last names of the person wanted before displaying the hit list.

© SAP AG TAW12 9-18

Keep in mind that the last name is used more frequently as a restriction than the first name.

If a carrier was already specified before the input help was called, only its employees are offered. Otherwise an input field on the input template for the carrier will be filled when you select the employee.

Make sure that the search help defined for the check table help of table ZEMPLOY## is used Check your success as described above.

1-2 You might want to offer further search paths for finding employees. To do this, take the following steps:

Copy search help SAREA to your new search help ZEMPLOY##_AREA. Change the parameters, selection method table, and data elements in your copy so that it references the names used in your table instead of the original table. Check and activate the search help.

Copy search help SDEPT to your new search help ZEMPLOY##_DEPT. Change as appropriate and activate (same as above).

Copy search help ZEMPLOY##_DEPT to ZEMPLOY##_CSH and convert the new copy to a collective search help. Add an importing parameter for AREA using the data element for that you created for ZEMPLOY##-Area. Include search helps ZEMPLOY##_ESH1, ZEMPLOY##_AREA, and ZEMPLOY##_DEPT as components of the new collective search help.

Change the search help defined for the check table help for table ZEMPLOY## and check your success.

1-3 Your business requirements have changed and it impacts the process of searching for employees. The search path with which employees can be found by their department is not currently required.

Change the input help used for field ZDEPMENT##-Department head accordingly without actually modifying search help ZEMPLOY##_CSH (or a table that is involved). Do this by creating an append search help for ZEMPLOY##_CSH. The append should include search help ZEMPLOY##_DEPT as a hidden search help. Check your success.

© SAP AG TAW12 9-19

Search Helps Solutions

Unit: Search Helps

1-1 Starting with the maintenance transaction for table ZDEPMENT##, call the F4 help as described. Go to the table maintenance screen for table ZDEPMENT##, select the field for department head, and call Goto → Search help → For field to verify that no search help has been assigned. Select the check table name for the field and you will be taken to the table maintenance screen for table ZEMPLOY##. Call Goto → Search help → For table to verify that no search help has been assigned. You find out that the input help is the check table help for table ZEMPLOY## and that it is a pure check table help (without a search help and without a text table).

To create search help ZEMPLOY##_ESH1:

1) Choose Search help in the initial screen of the ABAP Dictionary and enter ZEMPLOY##_ESH1 in the corresponding field.

2) Choose Create. In the next dialog box, confirm that you want to create an elementary search help.

3) Enter a short text for your search help.

4) The search help should support the search for employees. These are managed in table ZEMPLOY##. You therefore have to select this table (or a view on this table) as selection method. The table is sufficient for this exercise. Enter it in field Selection method.

5) To obtain the required behavior, choose dialog type Dialog with value restriction.

6) Choose the search help parameters using the F4 help. You should retain the hit list with the possible search help parameters by selecting Keep, since you do not have to call the help again in this case. Select fields Carrier, First name, Last name, and Personnel number as parameters.

7) Mark all parameters as EXPORT parameters (column EXP). Mark the attribute to be searched for (for example Personnel number) and the hierarchically higher Carrier as IMPORT parameters (Column IMP). This ensures that a corresponding entry in the input template is taken into consideration (as described in the exercise).

8) You can define the hit list by assigning the corresponding position numbers (for example 1, 2, 3, 4, 5) in column LPos.

9) You can define the dialog box for restricting values by assigning position numbers in column SPos. You should therefore enter positive numbers in these columns for parameters First name and Last name, where the value of Last name should be smaller than that of First name.

© SAP AG TAW12 9-20

10) Activate your search help. The search help is not yet effective for field ZDEPMENT##-Department head. However, you can try out the search help immediately with the Test function.

The search help you just created can only improve the check table help of table ZEMPLOY## (and thus the input help of field ZDEPMENT##-Department head) if it was attached to table ZEMPLOY##. You can do this as follows:

1) Go to change mode in the maintenance screen for this table. Choose Goto → Search help → For table. In the next dialog box, enter the name of search help ZEMPLOY##_ESH1. Choose Continue.

2) The proposal created by the system for assigning the search help parameters to the key fields of the table is probably correct. Check this and copy the definition.

Activate table ZEMPLOY##.

3) Call the Create entries function for table ZDEPMENT## again. The input help of field Department head should now behave as desired.

1-2 Proceed as follows:

1) At the Dictionary: Initial Screen, enter SAREA in the search help name field and hit the copy button. Change the to search help name to ZEMPLOY##_AREA and choose Continue. Choose change for the new search help.

2) Change the selection method table to ZEMPLOY##. Change parameter names to match the fields of the table by selecting the parameter and input help. This also corrects the data element reference. Correct other specifications as needed, syntax check the definition, and activate the search help.

Repeat steps 1 and 2 for creation of search help ZEMPLOY##_DEPT using SDEPT as the template.

3) Copy search help ZEMPLOY##_DEPT to ZEMPLOY##_CSH. At the maintain search help screen, choose Edit → Change search help type and confirm the change.

4) Add an importing parameter for AREA that uses the data element that you created for ZEMPLOY##-Area.

5) Select tab page Included search helps. Enter search help ZEMPLOY##_ESH1.

6) Position the cursor on the search help just entered. Choose Parameter assignment. Have the system make a proposal for the assignment.

7) The proposal is probably correct. To be on the safe side, check and then copy the proposal.

8) Repeat steps 4 – 6 for included search helps ZEMPLOY##_AREA and ZEMPLOY##_DEPT.

9) Activate search help ZEMPLOY##_CSH.

10) Go to the table maintenance screen for table ZEMPLOY## to change the search help for the table. Choose Goto → Search help → For table and change the search help name to ZEMPLOY##_CSH. Have the system make a proposal, check it, and copy it. Activate table ZEMPLOY##.

© SAP AG TAW12 9-21

By calling the input help for field ZDEPMENT##-Department head, you can see that the input help is still functioning and that a collective search help is now in effect.

1-3 Since you want to make the changes without modifying existing objects, you have to create an append search help for collective search help ZEMPLOY##_CSH. Proceed as follows:

1) In display mode, go to the maintenance screen for search help ZEMPLOY##_CSH. Choose Goto → Append search helps.

2) A name for the append search help is proposed in the next dialog box. You can copy this name.

3) Enter a short description for the append search help.

4) Select tab page Included search helps.

5) Enter ZEMPLOY##_DEPT in the list of included search helps. Mark column Hidden for the entry.

6) Position the cursor on the name of search help ZEMPLOY##_DEPT. Choose Parameter assignment. In the next dialog box, confirm that you want to create a proposal for the parameter assignment.

7) The parameter assignment proposed by the system is probably correct. Check this and copy the assignment.

8) Activate your append search help.

You can check your success by calling the input help for field ZDEPMENT##-Department head.

© SAP AG TAW12 10-1

SAP AG 1999

Appendix

l Flight model

l Decision tree for buffering

l Further information about search helps

l Important menu paths

l Index

© SAP AG TAW12 10-2

SAP AG 2002

Depart. airport

Arrival airport

Destination

Starting point

Tasks of the travel agency:• Possible airports• Possible carriers at the requested time• Possible flights at the requested time• Further information about the flights:price, bookings, ...

Flight Data Model for ABAP Training Courses

n One common flight data model is used in the ABAP training courses. Only a simple overview of this data model is shown here; details can be given if required.

n If you as a customer want to get from one place to another, you want to find out the following from your travel agency: � Which are the best airports for the given trip � At what times are there flights on the given day � Depending on your individual optimization conditions, what is the optimal solution, that is, the

best flight, the fastest connection, the connection that is nearest to the required arrival time. n This view is different from that of a travel agency: The data is stored in the data model in tables in a

central database according to technical criteria. The customer is not normally interested in all the required data (for example, you have to enter which customer booked which flights, when the bookings were made, how much the customer paid and so on) . The data must be entered depending on the user requirements using programs.

© SAP AG TAW12 10-3

SAP AG 2002

Airport

BC_AIRPORT T

Flight customer

BC_CUSTOM T

Airlinecarrier

BC_CARRIER T

Flight

BC_SFLIGHT T

City-airportassignment

BC_CITAIRP TCity

BC_GEOCITY T

Flight schedule

BC_PLANFLI T

Agency

BC_TRAVLAG T

Bookings

BC_BOOKING T

Salescounter

BC_COUNTER T

Time

H

A

A

CR

CR

H

R

R

H

H

Data Model

n Entities can be defined for all logically related information: The flight data model therefore contains an entity each for: � all cities � all airports � all carriers � all airports � all flights � The entities have a certain relationship to one another: � Flights start and end at an airport. � A flight is uniquely characterized by its carrier, departure airport, arrival airport, and flight time. � Flights can be offered on more than one day for each connection, but a flight can only be for a

certain connection. � All nearby airports must be assigned to the cities. � This data model manages all the required data without unnecessary redundancies and gives the

agency the data it requires.

© SAP AG TAW12 10-4

SAP AG 2002

SPFLI

Flight schedule

.....

SBOOK

Flight booking

.....

MANDTCARRIDCONNIDFLDATEBOOKIDCUSTOMIDCOUNTER AGENCYNUM

SFLIGHT

Flight

.....

MANDTCARRIDCONNIDFLDATESEATSMAXSEATSOCC

SCARR

Carrier

MANDTCARRIDCARRNAME

.....

Airlinecarrier

11001

Flight

11001

Flight schedule

11001

Bookings

11001

Time

H H H

H

MANDTCARRIDCONNIDAIRPFROMAIRPTODEPTIME

Implementation in the ABAP Dictionary

n The examples and exercises in the ABAP training courses and the ABAP documentation refer to the SAP flight data model. The Repository objects for the flight data model can be found in development class SAPBC_DATAMODEL.

n The following tables of the flight data model are mainly used in the ABAP training courses: ­ SPFLI: Table of flight connections ­ SFLIGHT: Table of flights ­ SBOOK: Table of flight bookings ­ SCARR: Table of airlines ­ SBUSPART: Table of airline partners ­ STRAVELAG: Table of travel agencies ­ SCUSTOM: Table of flight customers ­ SCOUNTER: Table of sales desks

© SAP AG TAW12 10-5

SAP AG 2002

No

Yes

Yes

Yes

Yes

No

Yes

No

No

No

Decision Tree for Buffering

Table may not be buffered.

Start

Full buffering

Single-record buffering

Buffering depends on installation.Further considerations must be made:Full or generic buffering possible?Secondary indexes or buffering?

Table may be buffered.

Generic buffering with suitable number of generic key fields

Are temp. inconsistencies in the read data acceptable? Are most

accesses read only?

Is the expected table sizesmaller than 8KB?

Is the table mostly accessed with SELECT SINGLE?

Is the expected table size larger than 1MB (>> 1000 records)?

Is a left-justified part of the key usually specified when

the table is accessed? Full buffering

© SAP AG TAW12 10-6

SAP AG 2002

Base table 1 Base table 2

DB view

Secondary table

Help view

Primary table

View as Selection Method of a Search Help

n If the selection method for a search help is a database view, the input help displays only the records for which there are entries in all the tables involved in the view (inner join). The set of possible entries is sometimes described by the entries in a primary table for which additional optional information can be added from further secondary tables. This view on the data can be implemented with a help view. The same outer join logic is used for help views as for maintenance views.

n A help view is defined analogously to a maintenance view. Help views can only be used as selection methods in search helps. Since the R/3 System cannot pass the selection directly to the database using a help view, it must generate its own access routines. The database view should therefore be used as selection method in preference to the help view.

n Selection using a table and text table corresponds to selection using a virtual help view. For this reason, a virtual help view should not be created in this case. Exception: The table contains a field having the same name as a non-key field of the text table. If this field of the text table is needed in the search help, you have to create a help view on the two tables because the field in the search help cannot be accessed directly.

n It is customary to start the name of help views with the prefix H_. Views beginning with the prefixes H_Y or H_Z therefore lie in the customer namespace.

© SAP AG TAW12 10-7

SAP AG 2002

Search help

Further Options for Search Helps

Default values Hot keys

Hide includedsearch helps

Display fields in the display box for restricting values

n A parameter can be pre-assigned a value by allocating a default value. The parameter is always given this value unless it is an IMPORT parameter that is linked with a field of the screen, its module pool or with a parameter of the including collective search help. The following can be default values: literals, system fields and GET parameters. You can use a default value to formulate a simple selection condition for a field of the selection method.

n A single letter or a digit can be assigned as hot key to an elementary search help. If this elementary search help is used in a screen field for the input help, and if this field has the short cut =<hot key>.<SEL1>.<SEL2>, when the input help is called, this elementary search help is processed. <SEL1>, <SEL2> is used as the field contents for the dialog box for restricting values (with an * added at the end) and the hit list is then displayed immediately.

n Individual search help inclusions can be hidden in a collective search help. You can thus deactivate individual search paths that are not wanted in a system. They should normally be hidden in an append search help as this can be done without modification.

n Parameters of an elementary search help can be marked as pure display fields in the dialog box for restricting values. In general, IMPORT parameters that are assigned unchangeable fields of the screen are displayed in this dialog box as unchangeable.

© SAP AG TAW12 10-8

SAP AG 2002

Date of flight F4F4

Carrier

. . .

Maintenance of Bookings

Flight number

Depart. city

Arrival city

. . .

SELECT * FROMSFLIGHT...

Search help exitSearch help exitSAPBC_GLOBAL_F4_SFLIGHTSAPBC_GLOBAL_F4_SFLIGHT

No.No. Depart. cityDepart. city FreeFree

CarrierCarrier

0555 Rome 147

0555 Rome 198

Alitalia

. . .. . .

Rome

AZ. . .. . .

. . .. . .

. . .. . .. . .. . .. . .. . . . . .. . .

Non-Standard: Search Help Exit

n A search help is an object that describes an input help within the system-wide standard. In some cases, the special semantics of a field requires that you deviate from this standard in some details. This can be implemented with a search help exit.

n A search help exit is a function module having a standardized interface. The function module F4IF_SHLP_EXIT_EXAMPLE can be used as template. If the search help has an exit, it is called before each single step of the process. The administrative data of the help processor is passed via the interface. The search help exit can manipulate this data.

n The administration data also includes the information about the next step to be executed. The search help exit can now execute either preparatory actions for this step or the step itself (for example, a data selection that cannot be implemented with a SELECT on a table or view). In the second case, the search help exit also changes the information about the next step to be executed.

n Some function modules that can be used as search help exits or that can be used to manipulate the administration data in search help exits are already defined with the prefix F4UT_.

n Search help exits should only be used for exceptions. Using search help exits encourages non-standard solutions and make it more difficult to maintain the input help.

© SAP AG TAW12 10-9

SAP AG 2002

Migration of Existing Input Helps

El. src. hlp.H_NAME

Selectionmethod

TableT

Search helpattachment

Help viewH_NAME

Primary table T

Second. tab. 1...

or

Help viewH_NAME

Primary table T

Second. tab. 1...

Coll. src. hlp.ABCD

Search helpinclusions

El. src. hlp.ABCDA

Selectionmethod

DB viewM_ABCDA

El. src. hlp.ZABCD1

Selectionmethod

DB viewM_ABCD1

DB viewM_ABCDA

MC object

ABCD

MC IDA generates

DB viewM_ABCD1

MC ID1 generates

Release 3.x

Release 4.x

belongs to

belongs to

n Search helps were introduced in Release 4.0. Previously, input helps were implemented by creating matchcodes and help views, which, however, had less functionality. When you upgrade to 4.x, search helps with the same name are created from these objects (if necessary, the name is preceded with a Y or Z). The original objects will initially remain in the system, but be meaningless.

n Prior to Release 4.0, a help view was a complete description of an input help that was automatically attached to its primary table (and only to it). An elementary search help is created from each help view. The primary table of the help view can be entered as the selection method for many cases, and the help view will be used for the others. The search help that is created is attached to the primary table of the help view.

n An elementary search help is created from a matchcode ID. The selection method assigned is the generated database view (for a transparent ID) or the generated pooled table (for a non-transparent ID) of the matchcode ID. In the first case, the generated view is administered as an independent object in the ABAP Dictionary. In the second case, the pooled table is still appended to its matchcode ID since the matchcode technique is used to update the data in this table.

n A collective search help is created from a matchcode object. Matchcodes were attached to input fields in the screen. These attachments are converted to attachments of the created collective search helps to the corresponding screen fields.

n The above graphic illustrates the migration for help views and for transparent matchcodes.

© SAP AG TAW12 10-10

SAP AG 2002

Alternative Displays of the Input Help

Input Help Control

List box

n The R/3 System recognizes three presentation forms for the input help: - List box - Control (modeless) - R/3 dialog (modal)

n The list box does not provide for any further selection conditions and no further columns are displayed in the hit list. However, the list box is the user-friendly input help for clear one-column lists. The application developer decides whether to offer a field as list box and stores this information in the Screen Painter for the corresponding field. When the user calls the list box, the data to be displayed is obtained with the input help mechanism stored in the ABAP Dictionary or Screen Painter for the field. You can obtain more information on using the list box in the course BC410 – Programming User Dialogs.

n Alternatively, you can display fields that are not offered as a list box with a modeless control or with a modal dialog implemented with R/3 screen technology. With Help ® Settings, each user can define the variant they prefer. This presentation form is then used for all input helps for this user. The system administrator can define the default value.

n The control is particularly useful if more than one field is to be filled sequentially with the same input help (for example in a table control). The Hold list function starts the control from the modal help.

© SAP AG TAW12 10-11

Important Menu Paths and Transactions

ABAP Dictionary Maintenance/Display Tools à ABAP Workbench à Development à Dictionary - Dictionary maintenance (SE11) - Dictionary display (SE12)

R/3 Repository Information System ABAP Dictionary

1. Tools à ABAP Workbench à Development à Dictionary (Dictionary object; Enter object name and choose operation) Environment à R/3 Repository Information System or

2. Tools à ABAP Workbench à Overview à R/3 Information System - R/3 Repository Information System (SE84) / Repository Information System ABAP Dictionary (SE15)

Data Display/Maintenance (Data Browser)

1. Tools à ABAP Workbench à Development à Dictionary (Dictionary object:Table, Enter table name and choose operation) Utilities à Table contents à Display or Table contents à Create entries or

2. Tools à ABAP Workbench à Overview à Data Browser Data display/maintenance (Data Browser) (SE16)

Index Tools à ABAP Workbench à Development à ABAP Dictionary (Dictionary object: table; Enter table name and choose operation) Goto à Indexes or Select Indexes...

Technical Settings Tools à ABAP Workbench à Development à ABAP Dictionary (Dictionary object: Table, enter table name and choose operation) Goto à Technical settings or Select Technical settings (SE13)

Database Utility Tools à ABAP Workbench à Development à ABAP Dictionary (Dictionary object: Enter object name and choose operation) Utilities à Database utility - Database utility (SE14)

Storage Parameters Tools à ABAP Workbench à Development à ABAP Dictionary (Dictionary object: Enter object name and select operation) Utilities à Database utility Goto à Storage parameters or Select Storage parameters - Database utility (SE14) à Goto à Storage parameters

Fixed Values Tools à ABAP Workbench à Development à ABAP Dictionary (Dictionary object: domain; Enter domain name and choose operation) Tab page Value range

Maintenance View Tools à ABAP Workbench à Development à Other tools à Table maint. view - Table view generation (SE54)

Enhanced Data Display Systemà Utilities à Table maintenance à Ext. table maint. - Extended table maintenance (SM30)

© SAP AG TAW12 10-12

Index

Dependent object 5-5

Activation 5-3

ALTER TABLE 6-4, 6-13

Analysis tool 6-11

Continue adjustment 6-11

Append structure 6-12, 6-13, 6-14, 7-12

Append search help 8-15

Restart log 6-9

Cluster table 6-14

Data class 2-8, 2-9

customer 2-9

Database 1-4, 2-3, 3-4

Database object 1-3, 1-7

Database system 3-4, 6-4, 7-11

Database table 1-3, 2-6

Database interface 1-7, 3-5

Database view 1-3, 1-4, 7-11, 7-14

Data element 1-3, 1-5, 2-4

Documentation 1-6

Domain 2-10, 4-3, 4-4

equality 4-9

Domain concept

two-level 2-5

Screen 1-3

Input help 1-3, 1-6, 8-3, 8-4, 11-10

Input check 1-6

Development environment 1-7

Extent 2-10

Field help 1-3, 1-6

Field assignment 4-7

Fixed value 4-3

Foreign key 1-6, 4-6, 4-7, 4-8, 4-10, 7-9, 7-13

Foreign key field

type of 4-11

© SAP AG TAW12 10-13

Foreign key relationship 4-11

Foreign key table 4-7, 4-8

Generation of table view 7-13

Size category 2-8, 2-10

Help view 11-6, 11-9

Include

structure 2-7, 5-5

in database views 7-12

Index 1-4, 3-3, 3-4, 8-12

Index entry 3-3

Index ID 3-4

Information system 5-7

Join 7-3

inner join 7-14

outer join 7-14

Join condition 7-5, 7-9, 7-10, 7-13

Catalog change 6-4

Cardinality 4-11

Component 1-5

Cross-product 7-4, 7-5

Customer field 6-12

Customer modification 6-13, 8-15

Runtime object 5-4, 6-3

Runtime environment 1-7

Matchcode 11-9

Object log 6-11

Optimizer 3-4

Pooled table 6-14

Performance 1-6, 3-5, 3-8, 8-12

Maintenance status 7-11

Help view 7-13, 7-14

Primary index 3-4

Primary key 2-3, 3-8, 4-8

Projection 7-3, 7-6

Log 1-6, 2-8, 2-11

Check field 4-7, 4-8, 4-9

Check table 4-4, 4-7, 4-8

© SAP AG TAW12 10-14

Buffer 3-5, 3-6, 3-7, 3-8, 3-9

Buffering 1-6, 2-8

full 3-6, 3-7, 3-8, 3-9

generic 3-6, 3-8

single-record 3-6, 3-9

of database view 7-11

Buffering type 3-6, 3-8, 7-11

Buffer synchronization 3-10, 3-11, 3-12, 3-13, 3-14, 3-15

Release upgrade 6-13

rdisp/bufreftime 3-10

Semantic attribute 4-11

Key 3-7

generic 3-8

reduce length of 6-8

Key field 3-4, 4-8

generic 3-8

Secondary index 3-4, 3-7

Selection 7-3, 7-4

Selection condition 7-7, 7-9

SE54 7-13

SPDD 6-13

Storage area 2-10

Lock object 1-6

Structure 1-3, 1-5, 2-3

Structure adjustment 6-4

Search field 8-4, 8-9

Search help 1-6, 8-5, 11-7

search help attachment 8-9, 8-10, 8-11, 8-14

elementary 8-14

collective search help 8-14, 8-15

append search help 8-15

dialog behavior of a search help 8-5, 8-7

search help parameter 8-7, 8-8

interface of a search help 8-5, 8-8, 8-9, 8-10, 8-14

selection method of a search help 8-5, 8-6

search help exit 11-8

Synchronization table 3-10, 3-11, 3-12, 3-13, 3-14, 3-15

© SAP AG TAW12 10-15

Synchronization time 3-14, 3-15

Table 1-3, 1-6, 2-3

transparent 2-6

text table 4-12

unlock 6-11

Table buffer 3-5, 3-6

Table type 1-3, 1-5

Table maintenance generator 7-13

Table-space 6-9, 6-10

Technical settings 2-8

Type

structured 2-6

user-defined 1-3, 1-5

Type definition 1-3, 1-5, 1-7

Conversion 6-4

terminated 6-9, 6-10

Conversion process 6-5, 6-6, 6-7, 6-8, 6-9

Unique index 3-4

Upgrade 6-13

Displacement 3-5

Version

active 5-3, 6-3, 6-5, 6-6, 6-7, 6-8, 6-9

inactive 6-3, 6-3, 6-5, 6-6, 6-7

Where-used list 5-6

View 1-4, 1-6, 7-3, 7-4, 7-5, 7-6, 7-7, 7-8, 7-9, 7-10, 7-11, 7-12, 7-13, 7-14, 11-6

Value table 4-4, 4-9, 4-10

$TAB 3-5

© SAP AG TAW12 11-1

SAP AG 2003

Complex: Techniques of List Processing

© SAP AG TAW12 11-2

SAP AG 2003

Course Content: Techniques of List Processing

Unit Introduction

Unit Outputting Data in Lists

Unit Selection screen

Unit Logical database

Unit Internal Data Collection

Unit Data Formatting and Control Level Processing

Unit Saving Lists and Background Processing

Unit Interactive Lists: Basics

Unit SAP Grid Control

Appendix

© SAP AG TAW12 12-1

SAP AG 1999

l Course Goals

l Course Objectives

l Course Content

l Course Overview Diagram

l Main Business Scenario

l Getting Started

Introduction

© SAP AG TAW12 12-2

SAP AG 2002

l Use utilities to create lists.

l Create print lists.

l Create both simple and interactive lists.

This course will prepare you to:

Course Goals

© SAP AG TAW12 12-3

SAP AG 2002

Course Objectives

At the conclusion of this course, you will be able to:

l Create formatted lists.

l Design a selection screen and evaluate user input.

l Read data from the database and use logical databases.

l Use internal tables and extract datasets to format data.

l Create simple interactive lists.

l Use the SAP Grid Control.

© SAP AG TAW12 12-4

SAP AG 2002

Tools Simple Lists Interactive Lists SAP Grid Control

Course Overview Diagram

CAR Id Departure Arrival

AA 0017 New York San FranciscoAA 0064 San Francisco New York LH 0400 Frankfurt New York LH 0402 Frankfurt Berlin

Connections of Airline LH 1AZ ROME TOKYO AZ TOKYO ROME AZDLDLLHLHLHLH

0789 12/29/2001 2,667,445 ITL 12/09/2001 2,667,445 ITL

AZ

© SAP AG TAW12 12-5

SAP AG 2002

Business Scenario

l You work for a tour operator.

l The company wants to improve its service.

l The company needs a list of the most current flight data to allow for an increase in bookings.

l You must write a program that displays the required flight data to a list.

© SAP AG TAW12 12-6

SAP AG 2002

Demonstrations, Copy Templates, and Solutions

l Development class BC405 with the following naming conventions:

n Demonstrations SAPBC405_xxxD_...

n Copy templates SAPBC405_xxxT_...

n Solutions SAPBC405_xxxS_...

n xxx Individual unit code

n Abbreviations for individual units: •FOL Unit 2: Outputting Data in Lists •SSC Unit 3: Selection Screen •LDB Unit 4: Logical Database •GDA Unit 5: Programming Data Retrieval •DAP Unit 6: Data Formatting and Control Level Processing •STL Unit 7: Saving Lists and Background Processing •ILB Unit 8: Basic Techniques in Interactive Lists •ALV Unit 9: ALV Grid Control

© SAP AG TAW12 12-7

SAP AG 2002

lWithout LDB (with copy template)

n Outputting Data in Lists

n Selection Screen

n Internal Data Collection

n Data Formatting and Control Level

Processing using internal tables

n Basic Techniques in Interactive

Lists

l With LDB (F1S)

n Logical Database

n Data Formatting and Control

Level Processing Using

Extract Datasets

n Saving Lists and

Background Processing

Exercises and Units

n Several of the units contain exercises. The sample solution provided for each exercise can be used for the subsequent exercise.

© SAP AG TAW12 13-1

SAP AG 2002

Outputting Data in Lists

Contents

l Simple Lists

l List Formats

l Page Layout

l Output Design

l Tools

© SAP AG TAW12 13-2

SAP AG 2002

At the conclusion of this unit, you will be able to:

Outputting Data in Lists: Objectives

l Structure a simple list

l Design your own list:

n Design the List Format

n Layout the page

n Design the output

© SAP AG TAW12 13-3

SAP AG 2002

Generating a List

REPORT sapbc405_fold_list_creation .

DATA: wa_spfli LIKE spfli.

START-OF-SELECTION.

SELECT carrid connid cityfrom cityto FROM spfli INTO (wa_spfli-carrid, …..

WRITE: / wa_spfli-carrid, wa_spfli-connid, wa_spfli-cityfrom, wa_spfli-cityto.

ENDSELECT.IF sy-subrc <> 0. … ENDIF.

DEMO: Generating a list 1

AA 0017 NEW YORK SAN FRANCISCOAA 0064 SAN FRANCISCO NEW YORK AZ 0555 ROME FRANKFURT AZ 0788 ROME TOKYO

: :

WRITE:WRITE:

n The first WRITE statement in an ABAP program triggers list generation. Output is directed to a list buffer and, when the buffer has been completely built, the system generates the screen image from the list buffer.

n As a standard function, the system generates two header lines (standard header). The first header line contains the program title from the program attributes in the upper-left corner and the page number in the upper-right corner. The second header line consists of an unbroken line. Both header lines remain in the window when you scroll.

n When you print a list, the first line of the header appears as follows: Upper-left: System date Center: Program title Upper-right: Page number

n Use transaction LIBS to display the SAP system list format suggestions. If you make your reports look as much like SAP reports as possible, your users will have a consistent look and feel between your custom reports and SAP reports.

© SAP AG TAW12 13-4

SAP AG 2002

DEMO: List format design 1

: :

DEMO: List format design 2

: :

50

12

Setting the List Format

REPORT <name> LINE-SIZE <s> LINE-COUNT <m[(n)]>.

REPORTREPORT sapbc405_fold_list_layoutlayout .

... WRITE: ...

REPORTREPORT LINELINE--SIZE 50SIZE 50LINELINE--COUNT 12COUNT 12.

AT LINE-SELECTION.CHECK NOT….NEW-PAGE LINE-SIZE 122

LINE-COUNT 65(3).WRITE …...

n The default report line width is 83 columns. The default page length is 60,000 lines. To override these defaults, use the additions LINE-SIZE <columns> and LINE-COUNT <lines_per_page> on the REPORT statement. Note that the values for lines per page and column width must be numbers and not data object names.

n You can override the default values for each list buffer by using the NEW-PAGE LINE-SIZE <columns> and/or LINE-COUNT <lines-per-page>. The width of a list can only be changed by creating a new list buffer. To return to the default values set <lines> and/or <columns> to zero.

n The use of LINE-COUNT <lines_per_page>(<footer_lines>) indicates that the page has a fixed number of lines part of which is reserved for use at the END-OF-PAGE event.

n The number of lines per page includes headings, detail, and footer lines. If the value of <lines_per_page> is less than the actual lines on the page, the report will terminate.

© SAP AG TAW12 13-5

SAP AG 2002

Page and Column Headers

List header

Column header

Standard headers TOP-OF-PAGE

REPORT sapbc405_fold_top_of_page NO STANDARD PAGE HEADING.NO STANDARD PAGE HEADING.

WRITE: / '************ ... '

START-OF-SELECTION....

Text elements

Title/Headings

Goto

List

System

List headers

EDITOR LIST

******************************

******************************

NO STANDARD PAGE HEADING.NO STANDARD PAGE HEADING.

TOPTOP--OFOF--PAGE.PAGE.

n You can maintain the list header and up to four column headers for a list. These standard page headers can be maintained either from the source code editor using the menu path Goto → Text Elements → List Heading or from the primary list buffer display using the menu path System → List → List Header. Maintaining the headers from the list display is helpful since the report output is visible. The new headings will automatically appear the next time the report is started. If you have not maintained the standard page headers, the system field SY-TITLE, which contains the program description from the program's attributes, is shown.

n The addition NO STANDARD PAGE HEADING in the REPORT/PROGRAM statement suppresses the output of list and column headers. You can override this global setting with NEW-PAGE NO-TITLE/WITH-TITLE and NO-HEADING/WITH-HEADING. As with all text elements, the headers can be translated later.

n The TOP-OF-PAGE event can be used to generate page headers. This is especially useful when you want to output variables in the headers. The event is triggered automatically in the primary list buffer when the first WRITE, ULINE, or SKIP keyword is encountered. If you do not suppress the standard list headers, they will appear above the lines generated by TOP-OF-PAGE. Lines generated by TOP-OF-PAGE remain in the window during vertical scrolling.

© SAP AG TAW12 13-6

SAP AG 2002

REPORT sapbc405_fold_format ... ....TOP-OF-PAGE.FORMAT COLOR COL_HEADING INTENSIFIED ONFORMAT COLOR COL_HEADING INTENSIFIED ON.WRITE: ...

FORMAT COLOR COL_HEADING INTENSIFIED OFF.WRITE: ...

START-OF-SELECTION.SELECT carrid connid cityfrom cityto deptime arrtimeINTO wa_spfli FROM spfli.WRITE: / wawa__spflispfli--carridcarrid COLOR COL_KEY INTENSIFIED ONCOLOR COL_KEY INTENSIFIED ON,

wawa__spflispfli--connidconnid COLOR COL_KEY INTENSIFIED ONCOLOR COL_KEY INTENSIFIED ON.FORMAT COLOR COL_NORMAL INTENSIFIED ON.WRITE: wa_spfli-cityfrom HOTSPOT ON,

wa_spfli-cityto,wa_spfli-deptime HOTSPOT ON,wa_spfli-arrtime.

FORMAT RESETFORMAT RESET.ENDSELECT.

Defining Line and Field Formats

FORMAT COLOR COL_HEADING INTENSIFIED ONFORMAT COLOR COL_HEADING INTENSIFIED ON.

wawa__spflispfli--carridcarrid COLOR COL_KEY INTENSIFIED ONCOLOR COL_KEY INTENSIFIED ON,wawa__spflispfli--connidconnid COLOR COL_KEY INTENSIFIED ONCOLOR COL_KEY INTENSIFIED ON.

FORMAT RESET.FORMAT RESET.

n You can use any of the following FORMAT options: •COLOR <n> [ON|OFF] Colors the line background •INTENSIFIED [ON|OFF] Intensify colors YES|NO •INVERSE [ON|OFF] Inverse: Background/text color •HOTSPOT [ON|OFF] Display mouse pointer as hand and single click (see AT LINE-SELECTION) •INPUT [ON|OFF] Input field •RESET Resets all formats to their default values

n The formats set with FORMAT take effect with the next WRITE statement and remain in effect until they are turned off either with FORMAT COLOR OFF or FORMAT RESET. Note that using RESET turns off the standard setting of INTENSIFED ON. As a result, FORMAT COLOR OFF is typically a better choice.

n At each new event, the system resets all FORMAT options to their default values. n You can apply formatting options to individual fields as in WRITE WA_SPFLI COLOR COL_KEY.

This technique overrides the options set with the FORMAT keyword.

© SAP AG TAW12 13-7

SAP AG 2002

REPORT sapbc405_fold_write ... .* constants for positions of outputsCONSTANTS: POS2 TYPE I VALUE 12,

LEN_FDT TYPE I VALUE 10, "sflight-fldate...

WRITE ATAT: / sy-vline,pos2(pos2(lenlen__fdtfdt)) wa_sflight-fldate COLOR COL_KEY,

...(len_pri) wa_sflight-price CURRENCYCURRENCY wa_sflight-currency,(len_cur) wa_sflight-currency.

...

WRITE Statement: General Syntax

WRITE [AT] [/<pos(len)>] <f> <option1> <option2> ... .

CURRENCYCURRENCY

ATAT:pos2(pos2(lenlen__fdtfdt))

n NO-GAP Suppresses output of spaces after the <f> field. Fields output directly after each other appear without gaps.

n NO-ZERO If the contents of field <f> are equal to zero, only spaces are output. If the field is type C or N, spaces replace leading zeros.

n DD/MM/YY Overrides the date formatting rule defined at the User profile level. n CURRENCY <key> Formats currency fields based on rules defined in table TCURX. n UNIT <key> Formats quantity fields based on rules defined in table T0006. n USING EDIT MASK <mask> Outputs according to the formatting template<mask>. n UNDER <g> The output begins at the column in which field <g> was output. n LEFT-JUSTIFIED Left-justified output (default for types C, N, D, T, X). n CENTERED Centered output within the output length. n RIGHT-JUSTIFIED Right-justified output (standard for all number fields: I, P and F) n You can find a complete list of all WRITE options in the online documentation.

© SAP AG TAW12 13-8

SAP AG 2002

REPORT sapbc405_fold_icon_symbol_line.* INCLUDE <icon>* INCLUDE <symbol>.INCLUDE <list>.INCLUDE <list>....

* state of free seatsIF SEATSFREE < 1.

WRITE ICON_RED_LIGHT AS ICON.ICON_RED_LIGHT AS ICON.ELSEIF SEATSFREE > 1.

WRITE ICON_GREEN_LIGHT AS ICON.ICON_GREEN_LIGHT AS ICON.ENDIF.

* state of booked seatsIF WA_SFLIGHT-SEATSOCC < 10.

WRITE SYM_LEFT_HAND AS SYMBOL.SYM_LEFT_HAND AS SYMBOL.ENDIF.

Outputting Icons, Symbols, and Lines

INCLUDE <list>.INCLUDE <list>.

ICON_RED_LIGHT AS ICON.ICON_RED_LIGHT AS ICON.

ICON_GREEN_LIGHT AS ICON.ICON_GREEN_LIGHT AS ICON.

SYM_LEFT_HAND AS SYMBOL.SYM_LEFT_HAND AS SYMBOL.

n You can use the AS SYMBOL option of the WRITE statement to show symbols in lists. This requires the statement INCLUDE <SYMBOL>. You can also write icons in list using AS ICON on the WRITE statement. The include named <LIST> can be used instead of the individual include statements. The <LIST> include contains include statements for <SYMBOL>, <ICON>, <LINES>, and <COLOR>.

n You can find an overview of available symbols and icons in the online documentation or in the statement examples for WRITE.

n To generate a horizontal line, use the ULINE statement, system field sy-uline in a WRITE statement, or several minus signs in a WRITE statement. ULINE creates an underline the entire width of the report. Other options for ULINE are ULINE /25 which underlines from column 25 to the right margin and ULINE /25(30) which starts the underline in column 25 for 30 columns.

n To generate a vertical line, use system field sy-vline in a WRITE statement n To generate special lines, like the upper-right corner, use line_top_right_corner AS LINE. n You can use these elements to frame a list, to separate titles from a list with horizontal lines, to

separate columns with vertical lines, and to create table and trees.

© SAP AG TAW12 13-9

SAP AG 2002

Scrolling in Lists and Lead Columns

SCROLL LIST [TO PAGE <p>][TO COLUMN <c>][TO LAST PAGE][<option>]...

SET LEFT SCROLL-BOUNDARY [COLUMN <c>].

REPORT sapbc405_fold_scroll_boundary ...

DATA: lsblsb_column_column TYPE i VALUE 10.

TOP-OF-PAGE.SET LEFT SCROLLSET LEFT SCROLL--BOUNDARYBOUNDARYCOLUMNCOLUMN lsblsb_column_column.

START-OF-SELECTION.......SCROLL LIST TO LAST PAGESCROLL LIST TO LAST PAGE.

9

SET LEFT SCROLLSET LEFT SCROLL--BOUNDARYBOUNDARYCOLUMNCOLUMN lsblsb_column_column.

SCROLL LIST TO LAST PAGESCROLL LIST TO LAST PAGE.

n You can use SET LEFT SCROLL-BOUNDARY COLUMN to freeze a fixed number of columns from the left margin. Without an additional parameter <number_of_columns>, the system uses the current write position (SY-COLNO) as the left margin to freeze.

n You must code this keyword in the TOP-OF-PAGE and TOP-OF-PAGE DURING LINE-SELECTION events since the system resets the value to zero at the end of each page.

n You can use NEW-LINE NO-SCROLLING to prevent the next list line from scrolling. This is useful to keep subheadings from scrolling while the detail lines scroll. This keyword can be combined with the SET LEFT SCROLL-BOUNDARY to freeze left margin columns on the report, resulting in a line that doesn't scroll while other lines scroll with frozen left margin columns.

n You can use the SCROLL keyword to scroll to any column or page in the list. Use of the extension INDEX <list_buffer_number> allows you to scroll in a specific list buffer. The following code will scroll the list buffer indicated by the current value of SY-LSIND to a specific page and line number on that page:

SCROLL LIST TO PAGE <page_number> INDEX sy-lsind LINE <line_number>

© SAP AG TAW12 13-10

SAP AG 2002

Additional Statements for Page Layout

SET BLANK LINES ON|OFF}.

POSITION <n>.

BACK.

SKIP [TO LINE] <n>.

NEW-LINE.

RESERVE <n> LINES.

NEW-PAGE.

n NEW-PAGE Creates a page break. n NEW-LINE Creates a line break and is the equivalent of "/" in a WRITE statement. n RESERVE <n> LINES If the current page does not have space for at least <n> more lines

in the list structure, a page feed is generated. n SKIP <n> <n> blank lines are output. n SKIP TO LINE <n> Positions the print cursor to line <n> on the current page. n BACK Positions the print cursor to the first line after the headers on the current page. n BACK (with RESERVE) When used with RESERVE, returns the print cursor to the line where

the RESERVE keyword was issued. n POSITION <n> Positions the print cursor to column <n> of the current line. n SET BLANK LINES ON Blank lines created by SKIP and blank fields are output. n SET BLANK LINES OFF No blank lines are output (default setting). n RESERVE, POSITION, and BACK are useful for printing mailing labels.

© SAP AG TAW12 13-11

SAP AG 2002

Multilingual List Elements

REPORT ...

WRITE:/ SY-VLINE,'Flight'(001),'Depature city'(002), 'Dest. city'(003),

...

REPORT ...

WRITE:/ SY-VLINE,'Flight'(001),'Depature city'(002), 'Dest. city'(003),

...

Source text Text elements

Title/Headings

Program

Text symbols

DE Flugverbindungen EN Flight ConnectionsFR ...

DE FlugEN FlightFR .....:

DE Startort

001

002

List header

Start the extended syntax check: Error if text elements are not maintained.Reconciliation: Program Text symbols possible.Determine text lengths with character list for other languages.

n Text elements include standard page headers, text symbols, and selection texts. The text elements are saved separately from the source text and in the language of the developer who wrote the report. This allows subsequent translation without touching the logic of the ABAP program. The user's logon language determines the language in which the system displays text elements.

n Define the output length of the text symbols as long as necessary, allowing sufficient space for translation into other languages.

n Text symbols can be addressed in programs in two ways: •WRITE TEXT-xxx (xxx is a three-character string) •literal text (xxx)

n An advantage to the second method of WRITE <literal text>(xxx) is that if there is no translation in the user's sign on language, the literal text will appear on the report rather than spaces.

n Use the extended program check to reconcile the text symbols with the program. You must select the check box for Character Strings. This box is not selected by default. If a text symbol has been maintained, it is always output in the list. The extended syntax check (transaction SLIN) returns an error if you forget to maintain the text symbols.

© SAP AG TAW12 13-12

SAP AG 1999

1

2

SY

-LIN

CT

SY-SCOLS

SY

-SR

OW

S

1122

33

SY-COLNO

SY-LINNO

SY-PAGNO

SY-LINSZ

System Fields in List Creation

n During generation of a list, the ABAP runtime system fills the following system fields: SY-LINCT Number of lines from REPORT statement (LINE-COUNT) SY-LINSZ Line width from REPORT statement (LINE-SIZE) SY-SROWS Number of lines in the display window SY-SCOLS Number of columns in the display window SY-PAGNO Page number of the current page SY-LINNO Line number of the current line of the current page (SY-PAGNO) SY-COLNO Column number of the current column

n During generation of the list, the system fills the last three system fields continuously.

© SAP AG TAW12 13-13

SAP AG 2002

Standard List Functions

Back/Exit/Cancel

Scroll

Print

Find

SaveList

Save/Send

n A number of standard list functions are available in the standard list interface. This functionality is provided automatically for report programs.

© SAP AG TAW12 13-14

SAP AG 2002

Outputting Data in Lists: Unit Summary

You are now able to:

l Structure a simple list

l Design your own list:

n Design the List Format

n Layout the page

n Design the output

© SAP AG TAW12 13-15

Outputting Data in Lists Exercises

Unit: Outputting Data in Lists

Topic: Formatting

When you have completed these exercises, you will be able to:

• Define list formatting

• Set headers

• Set hard lead columns

• Create multiple page lists

1-1 Copy program template SAPBC405_FOLT_1 to Z##FOL1_... Sample solution for exercise: SAPBC405_FOLS_1.

The program template is structured as follows: The global data and selection screen are defined in the TOP include. A selection list for the airline codes is displayed on the selection screen. At START-OF-SELECTION, the system reads the data from the database to internal table it_flights using a database view. At END-OF-SELECTION, the system calls subroutine DATA_OUTPUT. Your task is to implement the data output.

1-2 Generate a list (see sample list).

1-2-1 The list should contain the following fields:

Airline code = wa_flights-carrid

Flight number = wa_flights-connid

Flight date = wa_flights-fldate

Departure city = wa_flights-cityfrom

Arrival city = wa_flights-cityto

Flight price = wa_flights-price

Local currency of airline = wa_flights-currency

Display the data according to the template.

1-2-2 In the TOP include, define the list width as 100 columns and suppress the standard list header.

1-2-3 Implement event TOP-OF-PAGE. Output the list and column headers here. Refer to the template for details. Use text elements to allow your texts to be translated. To position the elements, use constants that you declare in the TOP include.

1-3 Format the list.

© SAP AG TAW12 13-16

1-3-1 Set a page break so that a new page is created for every new flight connection. You can use the control structure ON CHANGE OF wa_flights-connid. NEW-PAGE. ENDON.

1-3-2 Flag the international flights (wa_flights-countryto <> wa_flights-countryfr) with an icon (ICON_BW_GIS) at the beginning of each line. You will need to add the INCLUDE for <icon>.

1-3-3 Output the list header in color COL_HEADING with intensive display, and the column headers in color COL_HEADING with a less intensive display. Output the key information (CARRID, CONNID) in color COL_KEY with intensive display and the list body in COL_NORMAL with intensive display. Use horizontal lines to separate the headers from the list body. Output the price as a currency amount.

Optional: Add a frame using sy-vline and ULINE as shown in the template.

1-3-4 Make sure that the airline code and connection number remain in view during horizontal scrolling. Make sure that the statement SET LEFT SCROLL-BOUNDARY is set for each page of the report.

© SAP AG TAW12 13-17

Template (Displaying Data in Lists)

Flight Data

Flight Date Departure City

Arrival City Price

@ AZ 0555 09/10/1999 ROME FRANKFURT 360,202 ITL

@ AZ 0555 11/10/1999 ROME FRANKFURT 360,202 ITL

@ AZ 0555 11/11/1999 ROME FRANKFURT 360,202 ITL

@ AZ 0555 12/11/1999 ROME FRANKFURT 360,202 ITL

@ AZ 0555 12/12/1999 ROME FRANKFURT 360,202 ITL

Flight Data

Flight Date Departure City

Arrival City Price

@ LH 0400 09/10/1999 FRANKFURT NEW YORK 672.50 DEM

@ LH 0400 11/10/1999 FRANKFURT NEW YORK NEW YORK

@ LH 0400 11/11/1999 FRANKFURT NEW YORK 672.50 DEM

@ LH 0400 12/11/1999 FRANKFURT NEW YORK 672.50 DEM

@ LH 0400 12/12/1999 FRANKFURT NEW YORK 672.50 DEM

@ LH 0400 12/18/1999 FRANKFURT NEW YORK

@ = ICON_ BW_GIS

© SAP AG TAW12 13-18

Outputting Data in Lists Solutions

Unit: Outputting Data in Lists

Topic: Formatting

*&---------------------------------------------------------------------*

*& Report SAPBC405_FOLS_1 *

*& *

*&---------------------------------------------------------------------*

*& Exercise 1; Outputting Data in Lists *

*& *

*&---------------------------------------------------------------------*

INCLUDE bc405_fols_1top.

*&---------------------------------------------------------------------*

*& Event TOP-OF-PAGE

*&---------------------------------------------------------------------*

TOP-OF-PAGE.

* Title

FORMAT COLOR COL_HEADING INTENSIFIED ON.

ULINE.

WRITE: / sy-vline,

'Flight data'(001),

AT line_size sy-vline.

ULINE.

* Column header

FORMAT COLOR COL_HEADING INTENSIFIED OFF.

WRITE: sy-vline, AT pos_c1 'Flight'(002).

* Fix left scroll boundary

SET LEFT SCROLL-BOUNDARY.

WRITE: 'Date'(003) ,

© SAP AG TAW12 13-19

'Departure location'(004),

'Arrival location'(005),

'Price'(006),

AT line_size sy-vline.

ULINE.

*&---------------------------------------------------------------------*

*& Event START-OF-SELECTION

*&---------------------------------------------------------------------*

START-OF-SELECTION.

* Filling internal table with flight data using a DDIC view.

SELECT * FROM dv_flights INTO TABLE it_flights

WHERE carrid IN so_car.

*&---------------------------------------------------------------------*

*& Event END-OF-SELECTION

*&---------------------------------------------------------------------*

END-OF-SELECTION.

SORT it_flights BY carrid connid fldate.

* Data output

PERFORM data_output.

*&---------------------------------------------------------------------*

*& Form DATA_OUTPUT

*&---------------------------------------------------------------------*

* List output of flight data

*----------------------------------------------------------------------*

FORM data_output.

* Loop at the internal table for writing data

LOOP AT it_flights INTO wa_flights.

* Get a new page if CONNID has changed.

ON CHANGE OF wa_flights-connid.

© SAP AG TAW12 13-20

NEW-PAGE.

ENDON.

* Mark international flights

FORMAT COLOR COL_KEY INTENSIFIED ON.

IF wa_flights-countryfr EQ wa_flights-countryto.

WRITE: / sy-vline, icon_space AS ICON CENTERED.

ELSE.

WRITE: / sy-vline, icon_bw_gis AS ICON CENTERED.

ENDIF.

* Data output

WRITE: wa_flights-carrid,

wa_flights-connid.

FORMAT COLOR COL_NORMAL INTENSIFIED OFF.

WRITE: wa_flights-fldate,

wa_flights-cityfrom,

wa_flights-cityto,

wa_flights-price CURRENCY wa_flights-currency,

wa_flights-currency,

AT line_size sy-vline.

ENDLOOP.

ENDFORM. " DATA_OUTPUT

*&---------------------------------------------------------------------*

*& Include BC405_FOLS_1TOP *

*& *

*&---------------------------------------------------------------------*

REPORT bc405_fols_1top LINE-SIZE 100 NO STANDARD PAGE HEADING.

* Include for using icons

INCLUDE <icon>.

© SAP AG TAW12 13-21

* Constants for writing position

CONSTANTS: pos_c1 TYPE i VALUE 6,

line_size TYPE i VALUE 100.

* Internal table like DDIC view DV_FLIGHTS

DATA: it_flights LIKE TABLE OF dv_flights,

wa_flights LIKE dv_flights.

* Selection screen

SELECT-OPTIONS so_car FOR wa_flights-carrid.

© SAP AG TAW12 14-1

SAP AG 2002

Selection Screen

Contents:

l Generate

l Design

l Input checks

l Variants

© SAP AG TAW12 14-2

SAP AG 2002

Selection Screen: Unit Objectives

l Generate selection screens, supply them with

default values, and display them.

l Execute input checks in the selection screen.

l Create variants.

At the conclusion of this unit, you will be able to:

© SAP AG TAW12 14-3

SAP AG 2002

Selection Screen: Overview

SELECTION-SCREEN BEGIN OF SCREEN 1100.BEGIN OF SCREEN 1100.PARAMETERS: ... .SELECT-OPTIONS: ... .

SELECTION-SCREEN END OF SCREEN 1100.END OF SCREEN 1100.. . .

CALL SELECTIONCALL SELECTION--SCREEN 1100.SCREEN 1100.

Default selection screen

Screen: 1000

Default selection screen

Screen: 1000

Selection Screen

Screen: 1100

Logical DatabaseLogical Database

Program-internalProgram-internal

Variant 1

Variant 1

Variant 1

Version 1

CALL SELECTION-SCREEN 1100.

BEGIN OF SCREEN 1100.

END OF SCREEN 1100.

SELECT-OPTIONS: ...

PARAMETERS: ...

NODES: ...

n Selection screens serve as the interface between the program and the user and are used to limit the amount of data to be read from the database.

n Logical databases supply selection screens whose concrete appearance is dependent on the specified node name (NODES<name>). Selection screen versions (if supplied by the logical database) offer a subset of default selection screens.

n You can use the declarative language elements PARAMETERS and SELECT-OPTIONS to generate a default selection screen (screen 1000) with input-ready fields.

n In addition to the default selection screen, you can create additional selection screens with SELECTION-SCREEN BEGIN OF .... and call them with CALL SELECTION-SCREEN. Note that the number range of 1000 through 1010 is reserved for use by SAP. In addition, in the HR module you are limited to screens numbered 9000 and higher.

n Create variants to save selection screen values that are used repeatedly. The variant can be recalled for use whenever it is needed. If a report is to run in a background work process, a variant is required.

© SAP AG TAW12 14-4

SAP AG 2002

Airline AA

Output name

Output local currency

Price (local currency): up to 500

500 to 1000

1000 to 1500

Declaring Fields with PARAMETERS

PARAMETERS: <f>[TYPE <type>][DECIMALS <n>][LIKE <f1>][MEMORY ID <pid>][OBLIGATORY][DEFAULT <value>][LOWER CASE][VALUE CHECK] [AS CHECKBOX][RADIOBUTTON GROUP <grp>]

REPORT sapbc405_sscd_checkbox_radiobutton.... .PARAMETERS: pa_carr LIKE sflight-carrid,

pa_name AS CHECKBOX DEFAULT 'X', pa_curr AS CHECKBOX DEFAULT 'X',pa_lim_1 RADIOBUTTON GROUP lim, pa_lim_2 RADIOBUTTON GROUP lim, pa_lim_3 RADIOBUTTON GROUP lim.

CONSTANTS mark VALUE 'X'.

* Check, if any checkbox has been selected IF pa_name EQ mark. ... . ENDDIF.IF pa_curr EQ mark. ... . ENDDIF.

* Check, which radiobutton has been selected CASE mark.

WHEN pa_lim_1. ... . WHEN pa_lim_2. ... . WHEN pa_lim_3. ... .

ENDCASE.

!

!

n The PARAMETERS keyword is a declarative language element. As in the case of the DATA statement, you can declare parameters with TYPE or LIKE. The system generates input-ready fields in the selection screen. The names of PARAMETERS fields can be up to eight characters long. You can maintain selection texts using the menu path GOTO → TEXT ELEMENTS → SELECTION TEXTS.

n You can set a default value for a PARAMETERS keyword with the DEFAULT <value> addition. If you assign a MEMORY ID <pid>, the system retrieves the current value from SAP memory and supplies it on the screen automatically. If you declare mandatory fields with the OBLIGATORY addition, users cannot leave the selection screen until values have been entered in these fields.

n The automatic checking done by the Data Dictionary is turned off by default for report selection screens. However, if you make reference to a dictionary object that has a foreign key established, using VALUE CHECK will cause the dictionary to verify that the input is valid.

n You can also define parameters as checkboxes (AS CHECKBOX). Doing so creates a one-character field that can contain a " "(SPACE) or an X. You can evaluate the contents of checkboxes using IF/ENDIF control structures.

n You can also define a series of radio buttons for the selection screen with the addition RADIOBUTTON GROUP <grp>. The maximum length name for a RADIOBUTTON GROUP <grp> is four characters. Only one radio button in a group can be active and can be evaluated during program processing. You can evaluate the contents of radio buttons using CASE/ENDCASE control structures.

© SAP AG TAW12 14-5

SAP AG 2002

Selections with SELECT-OPTIONS

SELECT-OPTIONS: <seltab> FOR <f>.

Internal Tableso_carr

REPORT sapbc405_sscd_select_options .TABLES: sflight.SELECT-OPTIONS: so_carr FOR sflight-carrid DEFAULT 'AA',

so_fldt FOR sflight-fldate.

Airline AA

Flight date

to

toSign Option Low High

I EQ AA

n The SELECT-OPTIONS keyword is a declarative language element with the same eight character naming restriction as PARAMETERS. In contrast to the PARAMETERS keyword, SELECT-OPTIONS allows a range of values as well as complex selections instead of just a single input-ready field.

n The SELECT-OPTIONS keyword generates an internal table <seltab> with a standard structure and a header line. This table has four columns: sign, option, low, and high. Just as with PAREMETERS, you can maintain the selection text using the menu path Goto → Text elements → Selection texts.

n Use the addition FOR to specify the field against which the system should check the selection entries. This field must be declared in a DATA or TABLES statement. Both the high and low fields inherit the attributes of the referenced field.

n Each line of the selection table <seltab> formulates a condition using one of the following relational operators. The following values are possible:

SIGN: I (Include), E (Exclude) OPTION: EQ, NE, LE, LT, GE, GT, BT(Between), NB (Not Between), CP (Contains Pattern), NP (Contains Pattern not)

n The selection set is the union of all includes (I1,..., In) minus the union of all excludes (E1, ..., Em). If no values are entered in the SELECT-OPTIONS object, all rows are returned from the database

© SAP AG TAW12 14-6

SAP AG 2002

SELECT-OPTIONS with Multiple Selection Criteria

Selection options

Multiple selections

Sign Option Low High

I EQ AAI BT DL LH

1 E... 1 I... E... I...

AA

Airline AA to= Single value

Select

Greater than or equal

Less than or equal

n When the user makes entries in a SELECT-OPTIONS object, the system populates the internal table automatically.

n To change the default entries for the table fields SIGN and OPTION, choose Selection options pushbutton. The system offers all the alternatives that are appropriate for the selection. If the traffic signal icon is green during Select, there is an (I)nclusive in the sign column while a red light indicates (E)xclude.

n To delete a table entry, use the appropriate pushbutton (Delete selection). n Every selection criterion can be used to make multiple selections unless otherwise defined. If

multiple selections are present, the color of the arrow changes from white to green.

© SAP AG TAW12 14-7

SAP AG 2002

Syntax of the SELECT-OPTIONS Statement

SELECT-OPTIONS <seltab> FOR <f>

DEFAULT <value>

DEFAULT <value1> TO <value2>OPTION <xx> SIGN <x>

MEMORY ID <pid>

LOWER CASE

OBLIGATORY

NO-EXTENSION

NO INTERVALS

n Additions to the SELECT-OPTIONS statements are: l DEFAULT enables you to set default values for low or low and high parameters. You can use

OPTION and SIGN to set default values for option and sign that differ from the normal defaults. You can use either the INITIALIZATION or LOAD-OF-PROGRAM events to load default values to the internal table. For reasons of clarity, consider using one or the other rather than both in the same program.

l Value> addition. You can set a default value for a SELECT-OPTIONS keyword with the DEFAULT <value> addition. If you assign a MEMORY ID <pid>, the system retrieves the current value from SAP system memory and supplies it on the screen automatically. LOWER CASE suppresses conversion of the entry into upper-case. This addition is not permitted for Dictionary fields, since the attribute set in the Dictionary takes precedence.

l OBLIGATORY generates a mandatory field. A question mark appears in the entry field in the selection screen, and the user must enter a value.

l NO-EXTENSION suppresses multiple single or multiple range selections. l NO INTERVALS suppresses the seltab-high (upper interval limit) entry on the selection

screen. You can use the additional screen, Multiple selection, to enter ranges. n If you entered a logical database in the attributes of the type 1 program, the selection screen of the

logical database is processed. If you have programmed additional SELECTI-OPTIONS or PARAMETERS statements, the system displays them after the selections of the logical database.

© SAP AG TAW12 14-8

SAP AG 2002

Designing the Selection Screen I

SELECTION-SCREEN BEGIN OF BLOCK <block>

WITH FRAME TITLE <text>

SELECTION-SCREEN END OF BLOCK <block>

REPORT sapbc405_sscd_sel_screen_i.... SELECTION-SCREEN BEGIN OF BLOCK carr WITH FRAME.SELECT-OPTIONS: so_carr FOR wa_sflight-carrid.SELECTION-SCREEN END OF BLOCK carr.

SELECTION-SCREEN BEGIN OF BLOCK limit WITH FRAME TITLE text-001. PARAMETERS: pa_lim_1 RADIOBUTTON GROUP lim,

pa_lim_2 RADIOBUTTON GROUP lim, pa_lim_3 RADIOBUTTON GROUP lim.

SELECTION-SCREEN END OF BLOCK limit....

BEGIN OF BLOCKBEGIN OF BLOCK WITH FRAME TITLEWITH FRAME TITLE

END OF BLOCKEND OF BLOCK

Price ...

n You can use the SELECTION-SCREEN keyword to design the layout of the selection screen. n You can group screen elements that logically belong together with the extension BEGIN OF

BLOCK <block> and place a frame around them using WITH FRAME. Frames can be nested to a maximum depth of five.

n You can also assign a title to the block but only if you use a frame. The title can be declared as either text-xxx or as a three-character identifier. In the second case, you would define the text in the INITIALIZATION event with <xxx> = 'Frame Title'(<xxx>).

n Before designing a selection screen, you should become familiar with the screen design guidelines shown in transaction BIBS.

© SAP AG TAW12 14-9

SAP AG 2002

Designing the Selection Screen II

REPORT sapbc405_sscd_sel_screen_ii....* Parameters displayed in one line

SELECTION-SCREEN BEGIN OF LINE.SELECTION-SCREEN COMMENT 1(20) text-s03.SELECTION-SCREEN COMMENT pos_low(8) text-s04 FOR FIELD

pa_col.PARAMETERS pa_col AS CHECKBOX.SELECTION-SCREEN COMMENT pos_high(8) text-s05.PARAMETERS pa_ico AS CHECKBOX.

SELECTION-SCREEN END OF LINE.

SELECTION-SCREEN:

END OF LINE

COMMENT pos(len) <text> [FOR FIELD <f>]

POSITION pos

BEGIN OF LINE

Seats ...

Output ...

n You can display multiple parameters and comments on the same screen line. To do so, you must enclose them between the SELECTION-SCREEN BEGIN OF LINE and SELECTION-SCREEN END OF LINE statements. The COMMENT parameter enables you to include text in the line.

n Comment texts must always have a format (position and output length). The position can be set using a data field or pos_low or pos_high. These last two are the positions for SELECT-OPTIONS field low and high on the selection screen.

n Adding COMMENT ... FOR FIELD <f> ensures that the F1 Help for field <f> is displayed for the comment text and for the parameter itself. If you hide the parameter (selection variant: attribute invisible) the comment text is also hidden.

n You can use POSITION <pos> to set the cursor for the next output position (only within ... BEGIN OF LINE ... END OF LINE).

© SAP AG TAW12 14-10

SAP AG 2002

Initializing the Selection Screen

REPORT sapbc405_sscd_initialization....

INITIALIZATION.MOVE: mark TO pa_all.

MOVE: 'I' TO so_carr-sign, 'BT' TO so_carr-option, 'AA' TO so_carr-low, 'LH' TO so_carr-high.

APPEND so_carr.CLEAR so_carr.MOVE: 'E' TO so_carr-sign,

'EQ' TO so_carr-option, 'DL' TO so_carr-low.

APPEND so_carr....

INITIALIZATION.

Output ...

Selection Colors Icons

INITIALIZATION.INITIALIZATION.

Airline

Flight date

LHAA to

to

AllAvailableOccupied

Seats ...

n The INITIALIZATION and LOAD-OF-PROGRAM events are processed only once in an executable program. You can supply default values for the selection screen fields of a report, as well as those for a logical database, during this event. You can use F1 Help (Technical help) to determine the names of the selection fields if a logical database is attached to the program.

n The selection screen can also be supplied with values in the AT SELECTION-SCREEN OUTPUT event. This event happens just before the selection screen is initially displayed as well as when the screen is redisplayed after a warning or error message is issued.

© SAP AG TAW12 14-11

SAP AG 2002

Input Checks: AT SELECTION-SCREEN

REPORT sapbc405_sscd_at_sel_screen....

* Check of selection criterion SO_DEPT AT SELECTION-SCREEN ON so_dept.

IF ( so_dept-low LT '060000' AND so_dept-high LT '060000' ) OR ( so_dept-low GE '220000' AND so_dept-high GE '220000' ) AND city_fr EQ 'FRANKFURT'.

MESSAGE e046(bc405).ENDIF.

...

AT SELECTION-SCREEN

ON BLOCK <block>ON RADIOBUTTON GROUP <grp>

ON <f> ON <seltab>

n Validation of screen input can be done at the AT SELECTION-SCREEN event. If an error or warning message is displayed during this event, all screen fields are made ready for input.

n You can refer to individual selections with the parameters ON <f> or ON <seltab>. In case of errors, only these selections are made input-ready again.

n To check the entry combinations of a logical group, you can use the event AT SELECTION-SCREEN ON BLOCK <block>. Fields in this block are made ready for input when an error message is issued.

n The event AT SELECTION-SCREEN ON END OF <field> belongs to the PAI processing of the selection screen for multiple selections.

n You can perform entry checks for selection criteria of the logical database and for your own program-specific selections.

© SAP AG TAW12 14-12

SAP AG 2002

General Help and Possible Entries Help (F1 and F4)

AT SELECTION-SCREEN

ON HELP-REQUEST FOR <seltab>

ON VALUE-REQUEST FOR <seltab>

REPORT sapbc405_sscd_f1....

SELECT-OPTIONS: so_dept FOR spfli-deptime DEFAULT '080000' TO '220000'

NO-EXTENSION.

...

* Help request for SO_DEPT (F1 help).

AT SELECTION-SCREEN ON HELP-REQUEST FOR so_dept.CALL SCREEN 100 STARTING AT 30 03

ENDING AT 70 10.

ON HELPON HELP--REQUESTREQUEST

AbflugzeitEnter the departure time

in this field.

n You can program your own F1 (general help) and F4 (possible entries) at the events AT SELECTION-SCREEN ON HELP-REQUEST and AT SELECTION-SCREEN ON VALUE-REQUEST. Help can refer to individual parameters or a selection table (seltab). When you enter the name of a SELECT-OPTIONS table, you receive help for both seltab-low and seltab-high.

n After positioning the cursor and using the F1 or F4 key, the system triggers the appropriate event. n The addition of ON VALUE-REQUEST displays the pushbutton for F4 help for the corresponding

field. The value selection is controlled by interactive events.

© SAP AG TAW12 14-13

SAP AG 2002

CALL SELECTION-SCREEN

Selection screen: Screen 1000

Selection screen: Screen 1100

REPORT sapbc405_sscd_call_sel_screen.

... SELECTION-SCREEN:

BEGIN OF SCREEN 1100.PARAMETERS: pa_cus AS CHECKBOX,

pa_agy AS CHECKBOX.SELECTION-SCREEN:

END OF SCREEN 1100....

AT SELECTION-SCREEN ON pa_add.IF pa_add = mark.

START-OF-SELECTION.STARTING AT 5 5 ENDING AT 50 10.

IF sy-subrc <> 0.LEAVE TO SCREEN 1000.

ENDIF.ENDIF.

CALL SELECTION-SCREEN 1100

BEGIN OF SCREEN 1100.

END OF SCREEN 1100.

n You can work with several selection screens in one program. The default selection screen always has the screen number 1000. The screen numbers 1000 through 1010 are reserved for SAP usage. In addition, the HR modules of the R/3 system only permit screen numbers 9000 through 9999.

n You can also define alternate selection screens with SELECTION-SCREEN BEGIN OF SCREEN <nnnn> ... END OF SCREEN <nnnn>. Between the BEGIN ... END ... statements, you declare the required selections with SELECT-OPTIONS and PARAMETERS. The selection screen is called with CALL SELECTION-SCREEN <nnnn>.

n The system takes care of the return from the selection screen, which means you do not have to program it yourself with LEAVE SCREEN (as is the case with CALL SCREEN). The program continues with the next statement following the call. The system field SY-SUBRC will equal zero if the user pressed Execute or F8. If the User presses cancel or exit, SY-SUBRC contains a value of four.

n You can supply the selection screen with default values at INITIALIZATION. n Use the system field SY-DYNNR in the selection screen events to determine which screen is being

processed.

© SAP AG TAW12 14-14

SAP AG 2002

Selection Screen: Variants I

Program

Variants Displaychange

...SSCD_VARIANTS

ABAP Editor

Selection Screen

For all selectionscreens

For singleselection screens

Save asvariant

Subobjects

DEMO ...SSCD_VARIANTS

n Users can create any number of variants for a program. The variants are uniquely allocated to the program and cannot be shared with other programs.

n Creating variants makes sense when you frequently start a program with the same selection default values.

n If you select Start With Variant in the program attributes, the system forces the user to select a variant when running the program.

n If the program uses several selection screens, you can create a variant for all the selection screens or individually for each selection screen.

n Naming conventions and transporting variants l SAP&xxx are supplied by SAP system l CUS&xxx are created by customers (in client 000)

Variants that follow these naming conventions are client-independent and will automatically be transported along with the report. If these naming conventions are not followed, an entry for a request (task) must be added to the object list.

© SAP AG TAW12 14-15

SAP AG 2002

• Variant•Only for background processing•Protect variants•Display only in catalog•System variant (automatic transport)

• Field attributes•Required field•Deactivate SPA/GPA•Save field without values•Selection variable•Hide TO field•Hide field•Protect field

Selection Screen: Variants II

Attributes

n You are required to assign a name and a description to each variant. By default, variants are available for both online and background processing. You can also define a variant exclusively for use with background processing.

n You can protect the variant itself and the individual selection criteria and parameters against unauthorized changes. If you select Display only in catalog, this variant will not be displayed in the general value help (F4).

n The type of a selection is determined in its declaration (type s for SELECT-OPTIONS and, type p for PARAMETERS). If you select Selections protected, then the field(s) will not be ready for input. You can use the hide attribute to suppress selection criteria and parameters on the screen, if required, resulting in a less cluttered selection screen.

n When you use selection variables, there are three basic ways of supplying your selections with values at runtime: l From table TVARV (type T) l Date fields using dynamic date calculation (type D), such as today's date l User-specific variables (type B). (the selection must be declared with the MEMORY ID

<pid> addition).

© SAP AG TAW12 14-16

SAP AG 2002

Selection Screen: Unit Summary

You are now able to:

l Generate selection screens, supply them with default values, and display them.

l Execute input checks in the selection screen.

l Create variants.

© SAP AG TAW12 14-17

Selection Screen Exercises

Unit: Selection Screen

Topic: Designing, initializing (optional) and

checking (optional) a selection screen

When you have completed these exercises, you will be able to:

• Use the SELECT-OPTIONS statement

• Use the PARAMETERS statement

• Design a selection screen

• Initialize and check (optional)

1-1 Copy or enhance your program Z##FOL1_..., or copy the sample solution, SAPBC405_FOLS_1, to program Z##SSC1_... . Sample solution for exercise: SAPBC405_SSCS_1.

Extend the selection screen with SELECT-OPTIONS for the connection number and the flight date, as well as parameters for output control.

1-1-1 Extend the selection screen with a select options for the connection number and the flight date.

1-1-2 Suppress the multiple selection option for the flight date.

1-1-3 Enclose the selections for the airline carrier ID and the connection number within a frame that has a title.

Enclose the Group the flight date into a block. Create a frame with a title around the block.

1-1-4 Maintain the selection texts for all selection screen fields.

1-2 Implement a group of parameters for output control

1-2-1 Create group of three radio buttons with the following functionality

• all flights are read

• domestic flights only are read

• international flights only are read

The default setting should be for international flights.

1-2-2 Create an additional parameter for country code referencing wa_flights_countryfr and require the user to enter a value if domestic flights is selected.

1-2-3 Create a frame without a title around the radio button set. Create a frame around the complete display parameters and assign a title and selection texts. Arrange the frames and texts as shown in the template.

© SAP AG TAW12 14-18

1-3 Make sure that only the data records requested are read from the database.

1-3-1 To do this, supplement the WHERE clause of the SELECT statement with the conditions that result from the selections.

1-3-2 Implement the logic for the radio button group.

Note: You need three separate SELECT statements with different WHERE conditions. You can map the national/international condition directly on the database:countryto = dv_flights~countryfr or countryto <> dv_flights~countryfr. You use the tilde (~) to address the database field.

1-4 OPTIONAL

1-4-1 Initialize the selection table for the airline name such that the flights of airlines AA through QF will be displayed, but not AZ.

1-4-2 Display error message 003 in message class BC405 if the user has selected domestic flights and the input parameter for the country is initial. In case of error, only the radio button group and the country parameter should be ready for input.

© SAP AG TAW12 14-19

Selection Screen Solutions

Unit: Selection Screen

Topic: Designing, initializing (optional) and

checking (optional) a selection screen

*&---------------------------------------------------------------------*

*& Report SAPBC405_SSCS_1 *

*& *

*&---------------------------------------------------------------------*

*& Solution: Exercise 1; Selection Screen *

*& *

*&---------------------------------------------------------------------*

INCLUDE bc405_sscs_1top.

*&---------------------------------------------------------------------*

*& Event TOP-OF-PAGE

*&---------------------------------------------------------------------*

TOP-OF-PAGE.

* Title

FORMAT COLOR COL_HEADING INTENSIFIED ON.

ULINE.

WRITE: / sy-vline,

'Flight data'(001),

AT line_size sy-vline.

ULINE.

* Column header

FORMAT COLOR COL_HEADING INTENSIFIED OFF.

WRITE: sy-vline, AT pos_c1 'Flight'(002).

* Fix left scroll boundary

SET LEFT SCROLL-BOUNDARY.

WRITE: 'Date'(003) ,

© SAP AG TAW12 14-20

'Departure location'(004),

'Arrival location'(005),

'Price'(006),

AT line_size sy-vline.

ULINE.

*********************************************************************

Optional parts: Initializing and checking a selection screen

*********************************************************************

*&---------------------------------------------------------------------*

*& Event INITIALIZATION

*&---------------------------------------------------------------------*

INITIALIZATION. " OPTIONAL

* Initialize select-options for CARRID

MOVE: 'AA' TO so_car-low,

'QF' TO so_car-high,

'BT' TO so_car-option,

'I' TO so_car-sign.

APPEND so_car.

CLEAR so_car.

MOVE: 'AZ' TO so_car-low

'EQ' TO so_car-option,

'E' TO so_car-sign.

APPEND so_car.

CLEAR so_car.

*&---------------------------------------------------------------------*

*& Event AT SELECTION-SCREEN ON BLOCK PARAM

*&---------------------------------------------------------------------*

AT SELECTION-SCREEN ON BLOCK param. " OPTIONAL

* check country for national flights is not empty

CHECK national = 'X' AND country = space.

MESSAGE e003(bc405).

© SAP AG TAW12 14-21

*&---------------------------------------------------------------------*

*& Event START-OF-SELECTION

*&---------------------------------------------------------------------*

START-OF-SELECTION.

* Checking the output parameters

CASE mark.

WHEN all.

* Radiobutton ALL is marked

SELECT * FROM dv_flights INTO TABLE it_flights

WHERE carrid IN so_car

AND connid IN so_con

AND fldate IN so_fdt.

WHEN national.

* Radiobutton NATIONAL is marked

SELECT * FROM dv_flights INTO TABLE it_flights

WHERE carrid IN so_car

AND connid IN so_con

AND fldate IN so_fdt

AND countryto = dv_flights~countryfr

AND countryto = country.

WHEN internat.

* Radiobutton INTERNAT is marked

SELECT * FROM dv_flights INTO TABLE it_flights

WHERE carrid IN so_car

AND connid IN so_con

AND fldate IN so_fdt

AND countryto <> dv_flights~countryfr.

ENDCASE.

*&---------------------------------------------------------------------*

*& Event END-OF-SELECTION

*&---------------------------------------------------------------------*

END-OF-SELECTION.

© SAP AG TAW12 14-22

SORT it_flights BY carrid connid fldate.

* Data output

PERFORM data_output.

*&---------------------------------------------------------------------*

*& Form DATA_OUTPUT

*&---------------------------------------------------------------------*

* List output of flight data

*----------------------------------------------------------------------*

FORM data_output.

* Loop at the internal table for writing data

LOOP AT it_flights INTO wa_flights.

* Get a new page if CONNID has changed.

ON CHANGE OF wa_flights-connid.

NEW-PAGE.

ENDON.

* Mark international flights

FORMAT COLOR COL_KEY INTENSIFIED ON.

IF wa_flights-countryfr EQ wa_flights-countryto.

WRITE: / sy-vline, icon_space AS ICON CENTERED.

ELSE.

WRITE: / sy-vline, icon_bw_gis AS ICON CENTERED.

ENDIF.

* Data output

WRITE: wa_flights-carrid,

wa_flights-connid.

FORMAT COLOR COL_NORMAL INTENSIFIED OFF.

WRITE: wa_flights-fldate,

wa_flights-cityfrom,

wa_flights-cityto,

wa_flights-price CURRENCY wa_flights-currency,

© SAP AG TAW12 14-23

wa_flights-currency,

AT line_size sy-vline.

ENDLOOP.

ENDFORM. " DATA_OUTPUT

*&---------------------------------------------------------------------*

*& Include BC405_SSCS_1TOP *

*& *

*&---------------------------------------------------------------------*

REPORT bc405_sscs_1top LINE-SIZE 100 NO STANDARD PAGE HEADING.

* Include for using icons

INCLUDE <icon>.

* Constants for writing position

CONSTANTS : pos_c1 TYPE i VALUE 6,

line_size TYPE i VALUE 100.

* Constant for CASE statement

CONSTANTS mark VALUE 'X'.

* Internal table like DDIC view DV_FLIGHTS

DATA: it_flights LIKE TABLE OF dv_flights,

wa_flights LIKE dv_flights.

* Selections for connections

SELECTION-SCREEN BEGIN OF BLOCK conn

WITH FRAME TITLE text-tl1.

SELECT-OPTIONS: so_car FOR wa_flights-carrid,

so_con FOR wa_flights-connid.

SELECTION-SCREEN END OF BLOCK conn.

© SAP AG TAW12 14-24

* Selections for flights

SELECTION-SCREEN BEGIN OF BLOCK flight

WITH FRAME TITLE text-tl2.

SELECT-OPTIONS so_fdt FOR wa_flights-fldate NO-EXTENSION.

SELECTION-SCREEN END OF BLOCK flight.

* Output parameter

SELECTION-SCREEN BEGIN OF BLOCK param

WITH FRAME TITLE text-tl3.

SELECTION-SCREEN BEGIN OF BLOCK radio WITH FRAME.

PARAMETERS: all RADIOBUTTON GROUP rbg1,

national RADIOBUTTON GROUP rbg1,

internat RADIOBUTTON GROUP rbg1 DEFAULT 'X'.

SELECTION-SCREEN END OF BLOCK radio.

PARAMETERS country LIKE wa_flights-countryfr.

SELECTION-SCREEN END OF BLOCK param.

© SAP AG TAW12 15-1

SAP AG 2002

Logical Database

l Advantages of using a logical database

l Sub-objects of the logical database

l Data retrieval with logical databases

Contents:

© SAP AG TAW12 15-2

SAP AG 2002

At the conclusion of this unit, you will be able to:

Logical Database: Objectives

l Understand the advantages of using logical databases.

l Use logical databases.

l Identify program-specific characteristics in a logical database.

l Read data with a logical database.

© SAP AG TAW12 15-3

SAP AG 2002

DatabaseDatabase

Logicaldatabase

ABAP ProgramGET <node>

ABAP programOPEN SQL

ABAP programNATIVE SQL

Generating Lists

n In general, the system reads data that will appear in a list from the database. n You can use either OPEN SQL or NATIVE SQL statements to read data from the database. Native

SQL should be avoided in order to maintain portability from one RDBMS to another. In addition, Native SQL would need to be recoded to take advantage of upgrades in the RDBMS. OPEN SQL has no such limitations or requirements.

n The use of a logical database program provides you with an excellent alternative to programming the data retrieval yourself. Logical databases retrieve data records in primary key sequence and make them available to ABAP programs.They also offer a security advantage since the authority checks are done in the logical database program rather than in the report program.

© SAP AG TAW12 15-4

SAP AG 2002

Program 1Query 1

Logical database

Query 2

Program 2

Program 3

Program 6

Program 5

QuickView 1

Query 3

Query 4

QuickView 2

Program 4 - Provides a selection screen- Provides input and authorization

checks- Reads data records

Advantages of a Logical Database

n The same logical database can be the data source for several QuickViews, queries, and reports. In the QuickView, the logical database program (LDB) can be specified directly as a data source. A query works with the logical database when the InfoSet that generated the query is defined with a logical database. In the case of executable programs, the LDB is entered in the attributes or called using function module LDB_PROCESS. See appendix for information on how to use the function module.

n Logical databases offer several advantages over other methods of data retreival: � The system generates a selection screen. The use of selection screen versions or variants provides

the required flexibility. � The programmer does not need to know the exact structure or relationship of the tables involved;

the data is made available to the application program in primary key sequence. Data is formatted for output in the GET events. � Performance improvements within logical databases directly affect all programs linked to the

logical database without having to change the programs themselves. � Maintenance and enhancements can be performed at a central location. � Authorization checks are done in the logical database program rather than in the application

program.

© SAP AG TAW12 15-5

SAP AG 2002

ABAP DictionaryABAP Dictionary

F1SF1S

Hierarchical view

SPFLISPFLI

SFLIGHTSFLIGHT

SBOOKSBOOK

Logical Database: Overview

n A logical database is an ABAP program that reads data from the database and makes the data available to other report programs.

n A hierarchical structure determines the order in which the data is supplied to the programs. A logical database also provides a selection screen that checks user entries and conducts error dialogs. You can add your own parameters and select options.

n The SAP system provides approximately 190 logical databases in Release 4.6. The names of logical databases have been extended from three characters to 20 characters in Release 4.0 (namespace prefix max. 10 characters).

n If the logical database is three characters long, then the first two characters name the logical database and the third character identifies the application area. A list of the values for the third character can be displayed by looking at a program's attributes and then pressing F4 on the Application field. For example, DDF is named for Debtor Data and the letter F represents financial data.

© SAP AG TAW12 15-6

SAP AG 2002

Logical Database: F1S Nodes

Flight booking

MANDT

CARRID

CONNID

FLDATE

BOOKID

Flight schedule

MANDT

CARRID

CONNID

COUNTRYFR CITYFROM AIRPFROM COUNTRYTO CITYTO AIRPTO FLTIME DEPTIME ARRTIME DISTANCE DISTID FLTYPE PERIOD

SBOOKSPFLI SFLIGHT

Flights

MANDT

CARRID

CONNID

FLDATE

PRICE CURRENCYPLANETYPE SEATSMAX SEATSOCC PAYMENTSUM

CUSTOMIDCUSTTYPE SMOKER LUGGWEIGHT WUNIT INVOICE CLASS FORCURAM FORCURKEY LOCCURAM LOCCURKEY ORDER_DATE COUNTER AGENCYNUM CANCELLED

n The demo programs and exercises for ABAP courses and ABAP documentation refer to the SAP system's BC_TRAVEL flight data model, which is found in development class BC_DATAMODEL.

n The following tables form the nodes of logical database F1S: •SPFLI: Flight connections •SFLIGHT: Flights •SBOOK: Bookings

© SAP AG TAW12 15-7

SAP AG 2002

REPORT sapbc405_ldbd_simple_example.

NODES: spfli, sflight.

* Processing of SPFLI records GET spfli FIELDS ... .

* Processing of SFLIGHT records GET sflight FIELDS ... .

Sample Program for a Logical Database

ABAP: Program Attributes

Logical database

Selection screen version

F1S

n Only executable or report programs can use logical databases. You must enter the logical database name in the program's attributes.

n Use the keyword NODES <node> to specify the nodes of the logical database that you want to use in the program. NODES allocates the appropriate storage space for the node (a work area or a table area depending on the node type). Note that the keyword TABLES can still be used in release 4.6.

n When the logical database reads the data records, it issues the keyword PUT <node> which triggers the GET event in the report program. It is important to note that the GET <node> does not retrieve the data. It is simply an event like any other. As with other ABAP event keywords, the sequence in which these events are processed is determined by the structure of the logical database.

n It is important that you code the get event using the FIELDS extension. GET <node> is the equivalent of SELECT * which is unacceptable in terms of performance.

© SAP AG TAW12 15-8

SAP AG 2002

Establishes a data hierarchy (read sequence)Establishes a data hierarchy (read sequence)

Possible node types:Possible node types:

Database tableDatabase table Table or structure from the DDICTable or structure from the DDIC Name must beName must beidentical to the node name.identical to the node name.

DDIC type DDIC type DDIC type:DDIC type: Table or structure.Table or structure. Name canName candiffer from node name; deep structuresdiffer from node name; deep structuresare possible.are possible.

Data type Data type Type that was defined in a type group.Type that was defined in a type group.Dynamic typeDynamic type Type is specified in program.Type is specified in program.

LDB Sub-Objects: Structure

SPFLI

SBOOK

SFLIGHT

Table

Table

Table

Timetable

Flight table

Bookings

Name of node Node type Short text

n Logical databases are made up of several subobjects. The structure determines the hierarchy, and thus the read sequence of the data records.

n Node names can contain up to 14 characters. There are four different node types: � Table (type T): The node name is the name of a transparent table (this type corresponds to the

concept prior to Release 4.0A). The table name must be identical to the node name. Deep types (complex) are not allowed. � DDIC type (type S): Any node name is possible. The node is assigned a structure or a table type

from the Dictionary. The node name can differ from the type name. Deep structures are possible. � Type groups (type C): The node type is defined in a type group. The name of the type group must

be maintained in the Type group field. You should generally prefer DDIC types since the other applications that use the logical database (such as SAP Query) can access them (short texts, and so on). � Dynamic nodes (type A): These nodes do not have a fixed type; they are not classified until the

program runtime. The types that are allowed are determined when the structure is created.

© SAP AG TAW12 15-9

SAP AG 2002

START-OF-SELECTION

END-OF-SELECTION

SBOOK SBOOK SBOOK SBOOK

111

222

333

444

555

333 333 333 333

222444

111

SFLIGHT

SPFLI SPFLI

START-OF-SELECTION

GET SPFLI

GET SFLIGHT

GET SBOOK

GET SFLIGHT LATE

GET SFLIGHT

GET SBOOK

GET SBOOK

GET SBOOK

GET SBOOK

GET SFLIGHT LATE

GET SPFLI LATE

GET SPFLI

END-OF-SELECTION

DL 1699

25.02.2000

00002568

27.03.2000

00002569

00002570

00002590

00002591

DL 1984

REPORT sapbc405_ldbd_events....

11

22

33

44

22

33

44

55

11

33

33

33

Events in Logical Databases

SBOOK

SFLIGHT

n The START-OF-SELECTION event triggers before control is given to the read routine of the logical database. The END-OF-SELECTION event triggers after all GET events have been processed (all data records have been read and processed).

n The GET <node> event triggers whenever the logical database supplies data for this node. This means that GET events are processed several times, and that data has already been read from the database for these events. The sequence in which the GET events are processed is determined by the structure of the logical database.

n The GET <node> LATE event triggers when all subordinate nodes of node <node> have been processed, before the data is read for the next <node> (whenever a hierarchy level has been completed).

n At the start of the event, the system automatically adds a line feed and sets the font and intensity to the system defaults. If colors were set on in other events, they are reset as well.

© SAP AG TAW12 15-10

SAP AG 2002

START-OF-SELECTIONSTART-OF-SELECTION

GET <node>GET <node>

END-OF-SELECTIONEND-OF-SELECTION

Program Flow

Display list

Event Block Termination

Endsevent block.

ListDisplay

CHECKCHECK STOPSTOP EXITEXIT

Program Flow and Termination Alternatives

Endsevent block.

END-OF-SELECTIONis performed

n The CHECK keyword ends the current processing block if the condition is false. n The STOP keyword ends program processing. However, in contrast to the EXIT statement, the

processing block END-OF-SELECTION processes first (if it exists). n If there is a STOP statement within the END-OF-SELECTION processing block, program

processing ends and the list buffer is displayed. n The EXIT statement exits the program but does not do the END-OF-SELECTION event. Any list

buffer created before the EXIT keyword is encountered will be displayed. n You can also use the REJECT statement. The data record does not process further. Processing

continues on the same hierarchy level when the next data record is read. REJECT can also be used within a subroutine.

© SAP AG TAW12 15-11

SAP AG 2002

Selection include db<ldbname>sel:Definition of selection screen

SELECT-OPTIONS: ... .PARAMETERS: ... FOR NODE <node>.

LDB Sub-Objects: Selections

Allow dynamic selection

Fields are defined in dynamic selections using the selection view:Possible view origins are CUS and SAP.

Default selection screenScreen: 1000

Enable field selection

Define a selection screen version

n Logical database programs have an include named db<name>sel in which the logical database selection screen(s) are defined. The addition FOR NODE assigns selections to individual logical nodes. The appearance of a selection screen directly depends on the NODES statement contained within your program.

n A field selection can be defined in the logical database program for the individual nodes. This is done with the keyword FIELD SELECTION FOR NODE in the SELECTION-SCREEN statement. This code in the logical database program allows the application program to use the GET <node> FIELD <field list> to restrict the amount of data retrieved.

n Some logical databases also designate dynamic selections for individual nodes. This is done by dynamic selection using the addition DYNAMIC SELECTIONS FOR NODE. Dynamic selection button then appears on your report's selection screen. You can determine which selection fields can be set by choosing a particular selection view yourself (type: CUS) or by using the selection view delivered by the SAP system (type: SAP).

n Some large, logical databases have several selection screen versions. Each selection screen version contains a subset of the selection criteria (language element: EXCLUDE). You can specify which selection screen to display by entering the screen number in the program attributes.

© SAP AG TAW12 15-12

SAP AG 2002

Selections for node SPFLI

REPORT sapbc405_ldbd_simple_example.

NODES: spfli, sflight....

Selection Screen for the Logical Database

SPFLI

SBOOK

SFLIGHT

Structure of F1S

NODES:NODES: spflispfli,, sflightsflight..

Selections for node SFLIGHT

n When you enter a logical database in the attributes of your type 1 program, the system processes the selection screen of the logical database. The concrete characteristics of the selection screen depend upon the node specified in the NODES statement. If you specify a node of type T (table), you can also declare the table work area with the TABLES statement.

n If you address only subordinate nodes (in the hierarchy) of the logical database in the program (for example, SFLIGHT), the selection screen criteria for the superior node in the hierarchy (SPFLI) also appears. You can thus restrict the dataset to be read so that it meets your specific requirements.

n Note: A logical database always reads in accordance with its structure. This means that if you only need data from a node deep in the hierarchy, you should either find a different logical database where the desired node is higher in the structure or program the data retrieval yourself.

© SAP AG TAW12 15-13

SAP AG 2002

Dynamic Selections

Connection number

Special information

Airline carrier to

Logical Database: Dynamic Selections

Dynamic Selections

n If the logical database supports dynamic selections, Dynamic selections appears on the selection screen. When the user selects Dynamic selections, a second selection screen is displayed. This screen allows the user to select additional database fields. The system transfers the selections directly to the logical database program and to the database (dynamic selections).

n The selection view determines which fields are displayed on the selection screen. Create your own view with type CUS, and have it override the view with type SAP.

© SAP AG TAW12 15-14

SAP AG 2002

Naming conventionNaming convention sapdbsapdb<<ldbnameldbname>>

Database accesses, input checks, and authorization checksDatabase accesses, input checks, and authorization checks

sapdb<ldbname>

LDB Sub-Objects: Database Programs

FORM init....ENDFORM init.

FORM put_spfli....ENDFORM put_spfli.

FORM put_sflight....ENDFORM put_sflight.

ENDFORMENDFORM

FORMFORM

FORMFORM

FORMFORM

ENDFORMENDFORM

ENDFORMENDFORM

n The logical database programs are named SAPDB<ldbname> for logical database <ldbname> .The programs are a collection of subroutines, each of which is performed for specific events. For example, subroutine <init> is processed once at the start of the database program. This program can define default values for the selection screen of the LDB.

n Other subroutines also exist that are processed during events PBO (Process Before Output) and PAI (Process After Input) of the selection screen. Checks, such as authorization checks (AUTHORITY-CHECK), are usually performed during event PAI.

n The database accesses (SELECT statements) are programmed in the put_<node> subroutines. These subroutines may be processed several times, depending on which selection criteria the user specifies. The sequence in which these subroutines are processed is determined by the structure of the logical database.

© SAP AG TAW12 15-15

SAP AG 2002

REPORT sapbc405_ldbd_ldb.NODES: spfli, sflight, sbook.

Data processingData processing

Interaction: LDB and Program

SFLIGHT

SBOOK

SPFLI

FORM PUT_SPFLI.SELECT * FROM SPFLI ...PUT SPFLI.ENDSELECT.

ENDFORM.

FORM PUT_SFLIGHT.SELECT * FROM SFLIGHT .PUT SFLIGHT.ENDSELECT.

ENDFORM.

FORM PUT_SBOOK.SELECT * FROM SBOOK ...PUT SBOOK.ENDSELECT.

ENDFORM.

Structure of F1SStructure of F1S

* Processing of SPFLI records

* Processing of SFLIGHT records

* Processing of SBOOK records

PUT SBOOK.PUT SBOOK.

PUT SPFLI.PUT SPFLI.

PUT SFLIGHT.PUT SFLIGHT.

GET SBOOK FIELDS ...GET SBOOK FIELDS ...

GET SPFLI FIELDS ...GET SPFLI FIELDS ...

GET SFLIGHT FIELDS ...GET SFLIGHT FIELDS ...

PROGRAM SAPDBF1SDEFINING DATABASE F1S.

...

Data processingData processing

Data processingData processing

n When a report program that uses a logical database is started, control is initially passed to the database program of the logical database. Each event has a corresponding subroutine in the database program (for example, subroutine init for event INITIALIZATION). During the interaction between the LDB and the associated report, the subroutine is always processed first, followed by the event (if there is one in the report).

n Logical database programs read data from a database according to the structure declared for the logical database. They begin with the root node and then process the individual branches consecutively from top to bottom.

n The logical database reads the data in the PUT_<NODE> subroutines. During event PUT, control passes from the database program to the GET event of the associated report. The data is made available in the corresponding work areas in the report. The processing block defined for the GET event is performed. Control then returns to the logical database. PUT activates the next form subroutine found in the structure. This flow continues until the report collects all the available data.

n The depth of data read in the structure depends upon a program's GET events. A logical database reads to the lowest GET event contained within the structure attributes. Only those GET events for which processing is supposed to take place are written into the report program. Logical databases read all data records found on the direct access path.

© SAP AG TAW12 15-16

SAP AG 2002

CHECK <seltab>.

REPORT sapbc405_ldbd_check_sel.

NODES: spfli, sflight, sbook.SELECT-OPTIONS: sdepart FOR spfli-deptime

DEFAULT '08000' TO '230000',sprice FOR sflight-price DEFAULT '500' TO '1000'.

GET spfli FIELDS ...

GET sflight FIELDS fldate price currency.* check of selection criteria sprice

CHECK sprice....

GET sbook FIELDS ...

LDB selections

Checking Internal Program Selections

Dep. time 08:00:00 23:00:00

Price 500.00 1000.00

SELECTSELECT--OPTIONS:OPTIONS:

CHECKCHECK spricesprice..Negative CHECK

Positive CHECKSBOOK SBOOK

SFLIGHT SFLIGHT

Are dynamic selectionsallowed in this table?

SPFLI YES

SFLIGHT NO

n If you specify a logical database and declare additional selections in the program attributes that refer to the fields of a node not designated for dynamic selection, you must use the CHECK <seltab> statement to see if the current data record fulfills the selection criteria.

n If the data record does not fulfill these selection criteria, current event block processing ends.

© SAP AG TAW12 15-17

SAP AG 2002

You are now able to:

Logical Database: Unit Summary

l Understand the advantages of using logical databases.

l Use logical databases.

l Identify program-specific characteristics in a logical database.

l Read data with a logical database.

© SAP AG TAW12 15-18

Logical Database Exercises

Unit: Logical Databases

Topic: GET Events

When you have completed these exercises, you will be able to:

• Create a list with data read from a logical database.

1-1 Create program Z##LDB1_... with TOP include (Z##LDB1_...TOP) and enter logical database F1S in the program attributes. Make sure you specify Executable program as the program type. To do this, you must change the program type. Sample solution for exercise: SAPBC405_LDBS_1.

1-1-1 The logical database should supply the program with data for nodes SPFLI, SFLIGHT, and SBOOK.

1-1-2 Create a list that displays the following data:

Table SPFLI: CARRID, CONNID, CITYFROM, AIRPFROM, CITYTO, AIRPTO.

Table SFLIGHT: FLDATE, PRICE, CURRENCY, PLANETYPE, SEATSMAX, SEATSOCC,FREE_SEATS.

Table SBOOK: BOOKID, CUSTOMID, SMOKER, LUGGWEIGHT, WUNIT.

Field FREE_SEATS is not a table field – it has to be calculated in the program. The price and luggage weight should be output with the appropriate units.

1-1-3 Create a three line list in which each line outputs the information for one node (see above).

1-1-4 The list should have 83 columns. Maintain the column headers (standard list header).

1-1-5 Format the list (optional)

Output the first line in color COL_HEADING not intensified, the second line in COL_NORMAL intensified, and the third line in COL_NORMAL not intensified. Buffer the list.

Note: To output the fields, use the pattern functions available in the ABAP Editor.

© SAP AG TAW12 15-19

Exercises

Unit: Logical Databases

Topic: GET LATE Events and Checks from Internal Program Selections

When you have completed these exercises, you will be able to:

• Create a list with data read from a logical database.

• Check internal selections for their validity

2-1 Extend program Z##LDB1_... or copy the sample program SAPBC405_LDBS_1 to program Z##LDB2_... . Sample solution for exercise: SAPBC405_LDBS_2.

2-1-1 Add a SELECT-OPTIONS statement for the posting date (SBOOK-ORDER_DATE) to the selection screen. Frame the selection and maintain the selection text.

2-1-2 Make sure that only bookings that meet the specified selection criteria are output in the list. Include the booking date in the list output.

2-1-3 Maintain the column header (standard list header). In the list, output a solid line when all the bookings for a date have been output and when a flight has been completely output. Display each flight on a new page.

2-2 Optional

Sample solution for exercise: SAPBC405_LDBS_2_OPT.

2-3 Enhance your program.

2-3-1 Add a radio-button group with two radio buttons to the selection screen. Draw a frame around this group and maintain the selection texts.

The group has to model the following functionality: The user can select between charter flights only and regular flights only in the list. Whether a flight is a charter or not is determined in field SPFLI-FLTYPE: Charter flight: SPFLI –FLTYPE = 'X'.

2-3-2 Make sure that only dates and bookings that meet the specified selection criteria are output in the list.

© SAP AG TAW12 15-20

Logical Database Solutions

Unit: Logical Databases

Topic: GET Events

*&---------------------------------------------------------------------*

*& Report SAPBC405_LDBS_1 *

*& *

*&---------------------------------------------------------------------*

*& *

*& *

*&---------------------------------------------------------------------*

INCLUDE bc405_ldbs_1top.

*&---------------------------------------------------------------------*

*& Event GET SPFLI

*&---------------------------------------------------------------------*

GET spfli.

* Data output SPFLI

FORMAT COLOR COL_HEADING INTENSIFIED OFF.

WRITE: / sy-vline, spfli-carrid,

spfli-connid,

spfli-cityfrom,

spfli-airpfrom,

spfli-cityto,

spfli-airpto,

AT line_size sy-vline.

*&---------------------------------------------------------------------*

*& Event GET SFLIGHT

*&---------------------------------------------------------------------*

GET sflight.

* Calculate free seats

free_seats = sflight-seatsmax - sflight-seatsocc.

* Data output SFLIGHT

FORMAT COLOR COL_NORMAL INTENSIFIED ON.

© SAP AG TAW12 15-21

WRITE: / sy-vline, sflight-fldate,

sflight-price CURRENCY sflight-currency,

sflight-currency,

sflight-planetype,

sflight-seatsmax,

sflight-seatsocc,

free_seats,

AT line_size sy-vline.

*&---------------------------------------------------------------------*

*& Event GET SBOOK

*&---------------------------------------------------------------------*

GET sbook.

FORMAT COLOR COL_NORMAL INTENSIFIED OFF.

WRITE: / sy-vline, sbook-bookid,

sbook-customid,

sbook-smoker,

sbook-luggweight UNIT sbook-wunit,

sbook-wunit, AT line_size sy-vline.

*&---------------------------------------------------------------------*

*& Include BC405_LDBS_1TOP *

*& *

*&---------------------------------------------------------------------*

REPORT sapbc405_ldbs_1 LINE-SIZE 83.

* Used nodes of the structure of the logical database F1S

NODES: spfli, sflight, sbook.

* Variables

DATA: free_seats LIKE sflight-seatsocc.

* Constants

CONSTANTS: line_size LIKE sy-linsz VALUE 83.

© SAP AG TAW12 15-22

Solutions

Unit: Logical Databases

Topic: GET LATE Events and Checks from Internal Program Selections

*&---------------------------------------------------------------------*

*& Report SAPBC405_LDBS_2 *

*& *

*&---------------------------------------------------------------------*

*& *

*& *

*&---------------------------------------------------------------------*

INCLUDE bc405_ldbs_2top.

*&---------------------------------------------------------------------*

*& Event GET SPFLI

*&---------------------------------------------------------------------*

GET spfli.

* Data output SPFLI

FORMAT COLOR COL_HEADING INTENSIFIED OFF.

WRITE: / sy-vline, spfli-carrid,

spfli-connid,

spfli-cityfrom,

spfli-airpfrom,

spfli-cityto,

spfli-airpto,

AT line_size sy-vline.

*&---------------------------------------------------------------------*

*& Event GET SFLIGHT

*&---------------------------------------------------------------------*

GET sflight.

* Calculate free seats

free_seats = sflight-seatsmax - sflight-seatsocc.

* Data output SFLIGHT

© SAP AG TAW12 15-23

FORMAT COLOR COL_NORMAL INTENSIFIED ON.

WRITE: / sy-vline, sflight-fldate,

sflight-price CURRENCY sflight-currency,

sflight-currency,

sflight-planetype,

sflight-seatsmax,

sflight-seatsocc,

free_seats,

AT line_size sy-vline.

*&---------------------------------------------------------------------*

*& Event GET SBOOK

*&---------------------------------------------------------------------*

GET sbook.

* Check select-option

CHECK so_odat.

FORMAT COLOR COL_NORMAL INTENSIFIED OFF.

WRITE: / sy-vline, sbook-bookid,

sbook-customid,

sbook-smoker,

sbook-luggweight UNIT sbook-wunit,

sbook-wunit,

sbook-order_date,

AT line_size sy-vline.

*&---------------------------------------------------------------------*

*& Event GET SPFLI LATE

*&---------------------------------------------------------------------*

GET spfli LATE.

ULINE.

NEW-PAGE.

*&---------------------------------------------------------------------*

*& Event GET SFLIGHT LATE

*&---------------------------------------------------------------------*

GET sflight LATE.

ULINE.

*&---------------------------------------------------------------------*

© SAP AG TAW12 15-24

*& Include BC405_LDBS_2TOP *

*& *

*&---------------------------------------------------------------------*

REPORT sapbc405_ldbs_2 LINE-SIZE 83.

* Used nodes of the structure of the logical database F1S

NODES: spfli, sflight, sbook.

* Additional selections

SELECTION-SCREEN BEGIN OF BLOCK order WITH FRAME.

SELECT-OPTIONS: so_odat FOR sbook-order_date.

SELECTION-SCREEN END OF BLOCK order.

* Variables

DATA: free_seats LIKE sflight-seatsocc.

* Constants

CONSTANTS: line_size LIKE sy-linsz VALUE 83.

Optional Exercises

*&---------------------------------------------------------------------*

*& Report SAPBC405_LDBS_2_OPT *

*& *

*&---------------------------------------------------------------------*

*& *

*& *

*&---------------------------------------------------------------------*

INCLUDE BC405_LDBS_2_OPTTOP.

*&---------------------------------------------------------------------*

*& Event GET SPFLI

*&---------------------------------------------------------------------*

GET spfli.

*++++++++++++++++++++++++++++++++> optional

© SAP AG TAW12 15-25

* Check radio button group using a help variable

* Flight type charter or scheduled)

CLEAR check_negative.

IF pa_fty1 = 'X'.

IF NOT spfli-fltype = pa_fty1.

check_negative = 'X'.

ENDIF.

ELSEIF pa_fty2 = 'X'.

IF NOT spfli-fltype = space.

check_negative = 'X'.

ENDIF.

ENDIF.

CHECK check_negative = space.

*<---------------------------------------------------------- optional

* Data output SPFLI

FORMAT COLOR COL_HEADING INTENSIFIED OFF.

WRITE: / sy-vline, spfli-carrid,

spfli-connid,

spfli-cityfrom,

spfli-airpfrom,

spfli-cityto,

spfli-airpto,

AT line_size sy-vline.

*&---------------------------------------------------------------------*

*& Event GET SFLIGHT

*&---------------------------------------------------------------------*

GET sflight.

* Calculate free seats

free_seats = sflight-seatsmax - sflight-seatsocc.

* Data output SFLIGHT

FORMAT COLOR COL_NORMAL INTENSIFIED ON.

WRITE: / sy-vline, sflight-fldate,

sflight-price CURRENCY sflight-currency,

sflight-currency,

sflight-planetype,

© SAP AG TAW12 15-26

sflight-seatsmax,

sflight-seatsocc,

free_seats,

AT line_size sy-vline.

*&---------------------------------------------------------------------*

*& Event GET SBOOK

*&---------------------------------------------------------------------*

GET sbook.

* Check select-option

CHECK so_odat.

FORMAT COLOR COL_NORMAL INTENSIFIED OFF.

WRITE: / sy-vline, sbook-bookid,

sbook-customid,

sbook-smoker,

sbook-luggweight UNIT sbook-wunit,

sbook-wunit,

sbook-order_date,

AT line_size sy-vline.

*&---------------------------------------------------------------------*

*& Event GET SPFLI LATE

*&---------------------------------------------------------------------*

GET spfli LATE.

ULINE.

NEW-PAGE.

*&---------------------------------------------------------------------*

*& Event GET SFLIGHT LATE

*&---------------------------------------------------------------------*

GET sflight LATE.

ULINE.

*&---------------------------------------------------------------------*

*& Include BC405_LDBS_2OPTTOP *

*& *

*&---------------------------------------------------------------------*

REPORT sapbc405_ldbs_2_opt LINE-SIZE 83.

* Used nodes of the structure of the logical database F1S

© SAP AG TAW12 15-27

NODES: spfli, sflight, sbook.

* Additional selections

SELECTION-SCREEN BEGIN OF BLOCK order WITH FRAME.

SELECT-OPTIONS: so_odat FOR sbook-order_date.

SELECTION-SCREEN END OF BLOCK order.

* Additional selections (optional part)

SELECTION-SCREEN BEGIN OF BLOCK type WITH FRAME.

PARAMETERS: pa_fty1 RADIOBUTTON GROUP ftyp,

pa_fty2 RADIOBUTTON GROUP ftyp.

SELECTION-SCREEN: END OF BLOCK type.

* Variables

DATA: free_seats LIKE sflight-seatsocc.

DATA check_negative.

* Constants

CONSTANTS: line_size LIKE sy-linsz VALUE 83.

© SAP AG TAW12 16-1

SAP AG 2002

Programming Data Retrieval

Contents:

l Read data from multiple transparent tables.

l Evaluate the best technique for optimal performance.

© SAP AG TAW12 16-2

SAP AG 2002

Data Retrieval: Objectives

At the conclusion of this unit, you will be able to:

l Implement database read accesses across multiple tables.

l Rate the different techniques with regard to optimized performance.

© SAP AG TAW12 16-3

SAP AG 2002

ABAP program

GET PUT

Logical DatabaseOpen SQLNative SQL

DatabaseDatabase

Data Retrieval: Internal

n Whenever a logical database cannot supply your program with all necessary data, you must program database access directly into the program itself. This can be done using either Open SQL or Native SQL statements.

n Open SQL is preferable to Native SQL since it is not database specific and guarantees that your program is independent of the database engine. Use of Open SQL allows for portability between different RDMBS systems or should your company change to a different database system. ABAP Open SQL is completely integrated in to the Workbench which provides syntax checking of SQL statements. ABAP Open SQL also allows the R/3 System to make use of data buffers where appropriate.

n Native SQL statements are bound into a program using: � EXEC SQL [PERFORMING <form>]. � <Native SQL statements>. � ENDEXEC

n Do NOT use Native SQL to change the R/3 System database. The referential integrity of the R/3 System data is maintained by the R/3 System programs. Using Native SQL can quite easily corrupt your data. If you must use Native SQL, consider putting the code in an include so that it can be modified more easily if your RDBMS changes. Restrict your Native SQL to Standard SQL (ISO9075:1992)

© SAP AG TAW12 16-4

SAP AG 2002

Database View in the ABAP DictionaryDatabase View in the ABAP Dictionary

INNER JOIN, OUTER JOININNER JOIN, OUTER JOIN

FOR ALL ENTRIESFOR ALL ENTRIES

Nested SELECT StatementsNested SELECT Statements

Reading Multiple Database Tables

n Reading multiple database tables requires careful consideration and considerable analysis to ensure that the data retrieval is efficient.

n To ensure optimal database performance, follow these general rules: � Keep the amount of selected data as small as possible. Use WHERE conditions on all SELECT

statements. Rather than accumulating values programmatically, see if you can use the SQL aggregate functions MIN, MAX, AVG, SUM, and COUNT(*). Use the DISTINCT phrase as opposed to an array fetch, sort, and DELETE ADJACENT DUPLICATES. Use subqueries and HAVING clauses where appropriate. Whenever possible, pass the data filtering and summarization off to the database engine rather than in your program logic. � Keep data transfer between the application server and the database to a minimum. Do not use

SELECT * in report programs. Instead, use a field list and ensure the fields are retrieved in the same sequence as they are defined in the data dictionary. � Never use CORRESPONDING to move data. � Reduce the number of database inquiries and avoid nested SELECT statements. � When coding a WHERE clause, ensure that the conditions match an existing database index

whenever possible. The database optimizer can only use an index for data retrieval up to the point where the index fields match the WHERE condition. Run a SQL trace (transaction ST05) and evaluate the result of the SQL you coded in your program.

© SAP AG TAW12 16-5

SAP AG 2002

Database View in the ABAP DictionaryDatabase View in the ABAP Dictionary

REPORT sapbc405_gdad_db_view.... SELECT carrid carrname connid

cityfrom cityto fldate seatsmax seatsocc

INTO TABLE itab_flightsFROM sv_flightsWHERE cityfrom IN so_cityf AND cityto IN so_cityt AND seatsocc < sv_flights~seatsmax

ORDER BY carrid connid fldate....

Dictionary: Database view sv_flights

Table Join conditions

View fieldssvsv_flights_flights

Reading Multiple Database Tables I

n You can create database views in the ABAP Dictionary. Views are typically application specific and allow you to work with multiple database tables. Database views are realized on the database as an INNER JOIN.

n From Release 4.0, forward, you can buffer database views. You can then read from views using the SAP System buffer on the relevant application server. The same rules apply when buffering views as when buffering tables.

n Database view advantages: � Central maintenance � Accessible to all users � Only one SELECT statement is required in the program

n One disadvantage of the view is its low flexibility.

© SAP AG TAW12 16-6

SAP AG 2003

REPORT sapbc405_gdad_inner_join_2tab.... SELECT spfli~carrid spfli~connid

spfli~cityfrom spfli~citytosflight~fldate sflight~seatsmaxsflight~seatsocc

INTO TABLE itab_flightsFROM spfli INNER JOIN sflight

ON spfli~carrid = sflight~carrid AND spfli~connid = sflight~connid

WHERE spfli~carrid IN so_carrAND spfli~connid IN so_conn.

...

INNER JOININNER JOIN

INNER JOIN

A

a1

a2

a2

B

b1

b2

b3

C

c1

c2

c3

A

a1

a2

a2

B

b1

b2

b3

D

d1

d2

d3

D

d1

d3

A

a1

a2

B

b1

b3

C

c1

c3

INNER JOININNER JOINONON

Reading Multiple Database Tables IIA

n The transparent database tables are combined to form one results table representing the resulting set of a join. The join conditions are applied to this results table. The resulting composite for an inner join logic contains those records that have matching records in each transparent table only.

n Join conditions are not limited to key fields. They can be declared using any fields with a foreign key relationship defined or, in some cases, between fields with a common domain.

n If columns from two tables have the same name, ensure that the field labels are unique by prefixing the table name or alias name.

n A table join is an efficient way to read from the database. The database decides which table is read first and which index is selected.

© SAP AG TAW12 16-7

SAP AG 2003

REPORT sapbc405_gdad_outer_join.... SELECT scarr~carrid scarr~carrname

spfli~connid spfli~cityfromspfli~cityto

INTO TABLE itab_flightsFROM scarr LEFT outer JOIN spfli

ON scarr~carrid = spfli~carrid ORDER BY scarr~carrid spfli~connid.

...

OUTER JOINOUTER JOIN

LEFT OUTER JOIN

D

d1

d2

d3

E

e1

e2

e3

A

a1

a2

a2

B

b1

b2

b3

C

c1

c2

c3

A

a1

a2

a2

D

d1

d2

d3

E

e1

e2

e3

A

a1

a2

a2

a2

B

b1

b2

b3

b3

C

c1

c2

c3

c3

LEFT OUTER JOINLEFT OUTER JOINONON

Reading Multiple Database Tables IIB

n With a LEFT OUTER JOIN, the results tables can also contain entries from the designated left-hand table without the presence of corresponding data records (join conditions) from the table on the right. These table fields are filled by the database with null values. However, the null values are initialized according to the ABAP type before they are added to your program.

n It makes sense to use a LEFT OUTER JOIN when data from the table on the left is required but there are no corresponding entries in the table on the right for this data. For example, sapbc405_gdad_outer_join: not all airlines (table scarr) have flights listed (table spfli), but all airline names are supposed to be displayed in the list.

n The following limitations apply for the Left Outer Join: � You can only have a table or a view to the right of the JOIN operator, you cannot have another

join statement � Only AND can be used as a logical operator in an ON condition. � Each comparison in the ON condition must contain a field from the table on the right. � If the FROM clause contains an Outer Join, then all ON conditions must contain at least one 'true'

JOIN condition (a condition that contains a field from tab1 and a field from tab2).

© SAP AG TAW12 16-8

SAP AG 2002

FOR ALL ENTRIESFOR ALL ENTRIES

REPORT sapbc405_gdad_for_all_entries.... .SELECT carrid connid ...INTO TABLE itab_spfli FROM spfliWHERE .... .

* Check, if at least one dataset is found IF sy-subrc ne 0. EXIT. ENDIF.

* Delete Duplicates

SELECT carrid connid fldate ...INTO TABLE itab_sflight FROM sflight FOR ALL ENTRIES IN itab_spfli WHERE carrid = itab_spfli-carrid AND connid = itab_spfli-connid.

.... .

itab_spli

where ( carrid = 'LH'and connid = '0400')

or ( carrid = 'LH'and connid = '0402')

or ( . . .

Conversion

LH

LH

0400 ...

0402 ...

FOR ALL ENTRIES INFOR ALL ENTRIES IN

IFIF sysy--subrc nesubrc ne 0. EXIT.0. EXIT. ENDIF.ENDIF.

Reading Multiple Database Tables III

SORTSORT itabitab__spflispfli..DELETE ADJACENT DUPLICATES FROMDELETE ADJACENT DUPLICATES FROM itabitab__spflispfli

n FOR ALL ENTRIES works with the database in a quantity-oriented manner. Initially, all data is collected in an internal table. You must evaluate the value of SY-SUBRC after each SELECT statement. If the result of the first array fetch returns no data, the following SELECT statements will retrieve all entries from the database.

n SELECT...FOR ALL ENTRIES IN <itab> is treated like a SELECT statement with an external OR condition (depending on the optimizer and profile parameters). The system only selects those table entries that meet the logical condition (WHERE carrid = itab_sflight-carrid), replacing the placeholders (itab_spfli-carrid) with values from each entry in the internal table itab_spfli. Note that itab_spfli-carrid is a placeholder, and not a component of the internal table. Duplicates are not allowed. The internal table can, in principle, be as large as you want it to be.

n Using FOR ALL ENTRIES is one way to approximate an SQL join or a database view. The join and the view will typically yield significantly better performance than FOR ALL ENTRIES.

© SAP AG TAW12 16-9

SAP AG 2002

Reading Multiple Database Tables IV

Nested SELECT StatementsNested SELECT Statements

REPORT sapbc405_gdad_nested_selects.... .SELECT carrid connid cityfrom ...INTO wa_spfli FROM spfli

WHERE cityfrom IN so_cityf AND cityto IN so_cityt.APPEND wa_spfli TO itab_spfli.

SELECT carrid connid fldate ...INTO wa_sflight FROM sflight

WHERE carrid = wa_spfli-carrid AND connid = wa_spfli-connid.APPEND wa_sflight TO itab_sflight.

SELECT carrid connid fldate bookid ...INTO wa_sbook FROM sbook WHERE carrid = wa_sflight-carrid AND connid = wa_sflight-connid AND fldate = wa_sflight-fldate.APPEND wa_sbook TO itab_sbook.

ENDSELECT.ENDSELECT.

ENDSELECT.... .

SELECTSELECT

SELECTSELECT

SELECTSELECT

ENDSELECT.ENDSELECT.ENDSELECT.ENDSELECT.

ENDSELECT.ENDSELECT.

n When reading data from multiple transparent tables, it is important to optimize performance of the database access. Another method for reading related tables is to use nested SELECT statements. This technique should be avoided and used only as a last resort when no other data retrieval method is possible. The biggest disadvantage of the nested SELECT is that the inner SELECT is executed for each record retrieved by the outer SELECT. This leads to very poor performance in client/server environments.

n From Release 4.0, forward, you can also work with subqueries. Refer to the online documentationfor more information.

© SAP AG TAW12 16-10

SAP AG 2002

Programming Data Retrieval: Summary

You are now able to:

l Implement database read accesses across multiple tables.

l Rate the different techniques with regard to optimized performance.

© SAP AG TAW12 16-11

Programming Data Retrieval Exercises

Unit: Programming Data Retrieval

Topic: Inner Join

When you have completed these exercises, you will be able to:

• Use an ABAP join to read data from several different DB tables.

1-1 Copy or enhance your program Z##SSC1_..., or copy the sample solution, SAPBC405_SSCS_1, to program Z##GDA1_... . Sample solution for exercise: SAPBC405_GDAS_1.

1-1-1 Replace the data collected through database view dv_flights with an internal INNER JOIN performed on the database.

1-2 Deactivate (mark with an asterix (*)) the three SELECT statements at START-OF-SELECTION. Program INNER JOINs that fill internal table it_flights with data from tables SPFLI and SFLIGHT in the database.

Note:

The structure of the internal table it_flights does not correspond exactly to the combination of tables SPFLI and SFLIGHT. You must ensure that the fields are copied to the fields of the same name in the target table.

© SAP AG TAW12 16-12

Programming Data Retrieval Solutions

Unit: Programming Data Retrieval

Topic: Inner Join

*&---------------------------------------------------------------------*

*& Report SAPBC405_GDAS_1 *

*& *

*&---------------------------------------------------------------------*

*& Solution: Exercise 1, Internal Data Collection

*& *

*&---------------------------------------------------------------------*

INCLUDE bc405_gdas_1top.

*&---------------------------------------------------------------------*

*& Event TOP-OF-PAGE

*&---------------------------------------------------------------------*

TOP-OF-PAGE.

* Title

FORMAT COLOR COL_HEADING INTENSIFIED ON.

ULINE.

WRITE: / sy-vline,

'Flight data'(001),

AT line_size sy-vline.

ULINE.

* Column header

FORMAT COLOR COL_HEADING INTENSIFIED OFF.

WRITE: sy-vline, AT pos_c1 'Flight'(002).

* Fix left scroll boundary

SET LEFT SCROLL-BOUNDARY.

WRITE: 'Date'(003) ,

© SAP AG TAW12 16-13

'Departure location'(004),

'Arrival location'(005),

'Price'(006),

AT line_size sy-vline.

ULINE.

*&---------------------------------------------------------------------*

*& Event INITIALIZATION

*&---------------------------------------------------------------------*

INITIALIZATION. " OPTIONAL

* Initialize select-options for CARRID

MOVE: 'AA' TO so_car-low,

'QF' TO so_car-high,

'BT' TO so_car-option,

'I' TO so_car-sign.

APPEND so_car.

CLEAR so_car.

MOVE: 'AZ' TO so_car-low,

'EQ' TO so_car-option,

'E' TO so_car-sign.

APPEND so_car.

CLEAR so_car.

*&---------------------------------------------------------------------*

*& Event AT SELECTION-SCREEN ON BLOCK PARAM

*&---------------------------------------------------------------------*

AT SELECTION-SCREEN ON BLOCK param. " OPTIONAL

* check country for national flights is not empty

CHECK national = 'X' AND country = space.

MESSAGE e003(bc405).

*&---------------------------------------------------------------------*

*& Event START-OF-SELECTION

*&---------------------------------------------------------------------*

© SAP AG TAW12 16-14

START-OF-SELECTION.

* Checking the output parameters

CASE mark.

WHEN all.

* Radiobutton ALL is marked

SELECT * FROM spfli INNER JOIN sflight

ON spfli~carrid = sflight~carrid

AND spfli~connid = sflight~connid

INTO CORRESPONDING FIELDS OF TABLE it_flights

WHERE spfli~carrid IN so_car

AND spfli~connid IN so_con

AND sflight~fldate IN so_fdt.

SORT it_flights BY carrid connid fldate.

WHEN national.

* Radiobutton NATIONAL is marked

SELECT * FROM spfli INNER JOIN sflight

ON spfli~carrid = sflight~carrid

AND spfli~connid = sflight~connid

INTO CORRESPONDING FIELDS OF TABLE it_flights

WHERE spfli~carrid IN so_car

AND spfli~connid IN so_con

AND sflight~fldate IN so_fdt

AND spfli~countryfr = spfli~countryto

AND spfli~countryfr = country.

SORT it_flights BY carrid connid fldate.

WHEN internat.

* Radiobutton INTERNAT is marked

SELECT * FROM spfli INNER JOIN sflight

ON spfli~carrid = sflight~carrid

AND spfli~connid = sflight~connid

INTO CORRESPONDING FIELDS OF TABLE it_flights

WHERE spfli~carrid IN so_car

© SAP AG TAW12 16-15

AND spfli~connid IN so_con

AND sflight~fldate IN so_fdt

AND spfli~countryfr NE spfli~countryto.

SORT it_flights BY carrid connid fldate.

ENDCASE.

* Additional solution: dynamical WHERE condition

* PERFORM get_data.

*&---------------------------------------------------------------------*

*& Event END-OF-SELECTION

*&---------------------------------------------------------------------*

END-OF-SELECTION.

* Data output

PERFORM data_output.

*&---------------------------------------------------------------------*

*& Form DATA_OUTPUT

*&---------------------------------------------------------------------*

* List output of flight data

*----------------------------------------------------------------------*

FORM data_output.

* Loop at the internal table for writing data

LOOP AT it_flights INTO wa_flights.

* Get a new page if CONNID has changed.

ON CHANGE OF wa_flights-connid.

NEW-PAGE.

ENDON.

* Mark international flights

FORMAT COLOR COL_KEY INTENSIFIED ON.

IF wa_flights-countryfr EQ wa_flights-countryto.

© SAP AG TAW12 16-16

WRITE: / sy-vline, icon_space AS ICON CENTERED.

ELSE.

WRITE: / sy-vline, icon_bw_gis AS ICON CENTERED.

ENDIF.

* Data output

WRITE: wa_flights-carrid,

wa_flights-connid.

FORMAT COLOR COL_NORMAL INTENSIFIED OFF.

WRITE: wa_flights-fldate,

wa_flights-cityfrom,

wa_flights-cityto,

wa_flights-price CURRENCY wa_flights-currency,

wa_flights-currency,

AT line_size sy-vline.

ENDLOOP.

ENDFORM. " DATA_OUTPUT

* <-------------- ADDITIONAL --------------> *

*&---------------------------------------------------------------------*

*& Form GET_DATA

*&---------------------------------------------------------------------*

* Instead of programming three different SELECT statements, these

* SELECTs can be combined in one dynamical WHERE condition.

**----------------------------------------------------------------------

*

*FORM GET_DATA. "#EC CALLED

*

* DATA: WHERE_LINE(40),

* WHERE_TAB LIKE TABLE OF WHERE_LINE.

*

** only national flights requested

* IF NATIONAL NE SPACE.

* WHERE_LINE = 'p~countryfr = p~countryto'. "#EC NOTEXT

© SAP AG TAW12 16-17

* APPEND WHERE_LINE TO WHERE_TAB.

* CONCATENATE 'AND p~countryfr =' "#EC NOTEXT

* '''' INTO WHERE_LINE

* SEPARATED BY SPACE.

* CONCATENATE WHERE_LINE COUNTRY '''' INTO WHERE_LINE.

* APPEND WHERE_LINE TO WHERE_TAB.

* ENDIF.

*

** only international flights requested

* IF INTERNAT NE SPACE.

* WHERE_LINE = 'p~countryfr NE p~countryto'. "#EC NOTEXT

* APPEND WHERE_LINE TO WHERE_TAB.

* ENDIF.

*

** Close WHERE-clause by dot

* WHERE_LINE = '.'.

* APPEND WHERE_LINE TO WHERE_TAB.

*

** Inner join with dynamical where clause

* SELECT P~CARRID P~CONNID

* P~COUNTRYFR P~CITYFROM P~AIRPFROM

* P~COUNTRYTO P~CITYTO P~AIRPTO

* F~FLDATE F~PRICE F~CURRENCY

* FROM SPFLI AS P JOIN SFLIGHT AS F

* ON P~CARRID = F~CARRID AND P~CONNID = F~CONNID

* INTO CORRESPONDING FIELDS OF TABLE IT_FLIGHTS

* WHERE P~CARRID IN SO_CAR

* AND P~CONNID IN SO_CON

* AND F~FLDATE IN SO_FDT

* AND (WHERE_TAB).

*

*ENDFORM. " GET_DATA

*&---------------------------------------------------------------------*

*& Include BC405_GDAS_1TOP *

*& *

*&---------------------------------------------------------------------*

© SAP AG TAW12 16-18

REPORT sapbc405_gdas_1 LINE-SIZE 100 NO STANDARD PAGE HEADING.

* Include for using icons

INCLUDE <icon>.

* Constants for writing position

CONSTANTS: pos_c1 TYPE i VALUE 6,

line_size TYPE i VALUE 100.

* Constant for CASE statement

CONSTANTS mark VALUE 'X'.

* Internal table like DDIC view DV_FLIGHTS

DATA: it_flights LIKE TABLE OF dv_flights,

wa_flights LIKE dv_flights.

* Selections for connections

SELECTION-SCREEN BEGIN OF BLOCK conn WITH FRAME TITLE text-tl1.

SELECT-OPTIONS: so_car FOR wa_flights-carrid,

so_con FOR wa_flights-connid.

SELECTION-SCREEN END OF BLOCK conn.

* Selections for flights

SELECTION-SCREEN BEGIN OF BLOCK flight WITH FRAME TITLE text-tl2.

SELECT-OPTIONS so_fdt FOR wa_flights-fldate NO-EXTENSION.

SELECTION-SCREEN END OF BLOCK flight.

* Output parameter

SELECTION-SCREEN BEGIN OF BLOCK param WITH FRAME TITLE text-tl3.

SELECTION-SCREEN BEGIN OF BLOCK radio WITH FRAME.

PARAMETERS: all RADIOBUTTON GROUP rbg1,

national RADIOBUTTON GROUP rbg1,

internat RADIOBUTTON GROUP rbg1 DEFAULT 'X'.

SELECTION-SCREEN END OF BLOCK radio.

PARAMETERS country LIKE wa_flights-countryfr.

SELECTION-SCREEN END OF BLOCK param.

© SAP AG TAW12 17-1

SAP AG 2002

Data Formatting and Control Level Processing

l Control Level Processing

l With Internal Tables

l With Extract Datasets

Contents:

© SAP AG TAW12 17-2

SAP AG 2002

At the conclusion of this unit, you will be able to:

Data Formatting and Control Level Processing: Unit Objectives

l Format data with internal tables.

l Use control level processing with internal tables and extract datasets.

© SAP AG TAW12 17-3

SAP AG 2003

Data Formatting and Control Level Processing

OverviewOverview

Internal TablesInternal Tables

Extract DatasetsExtract Datasets

Comparison of both TechniquesComparison of both Techniques

© SAP AG TAW12 17-4

SAP AG 2002

Data sets in an internal table From: To: Flight no.

BerlinFrankfurt

24022436

New York

002604000402

San Francisco

0454

SingaporeHong Kong

Control Level Processing

FrankfurtFrankfurt

FrankfurtFrankfurt

FrankfurtFrankfurt

FrankfurtFrankfurt

FrankfurtFrankfurt

FrankfurtFrankfurt

HongKon.

Berlin

Berlin

New York

New York

New York

San Francisco

Singapore

2402

2436

0026

0400

0402

0454

0863

n You can use control level processing to create structured lists. The data can then be group indicated to create a better list layout.

n The data to be displayed must be stored in an internal table and sorted in ascending sequence. You can also use an extract dataset for the same purpose. Both the internal table and the extract dataset offer distinct advantages.

© SAP AG TAW12 17-5

SAP AG 2003

Data Formatting and Control Level Processing

OverviewOverview

Internal TablesInternal Tables

Extract DatasetsExtract Datasets

Comparison of both TechniquesComparison of both Techniques

© SAP AG TAW12 17-6

SAP AG 2002

TYPES: BEGIN OF <linetype>,... END OF <linetype>.

DATA <itab> TYPE STANDARD TABLE OF <linetype>.

REPORT sapbc405dapd_a_internal_tables.

TYPES: BEGIN OF struct_conn,cityfrom LIKE spfli-cityfrom,cityto LIKE spfli-cityto,carrid LIKE spfli-carrid,deptime LIKE spfli-deptime,arrtime LIKE spfli-arrtime,

END OF struct_conn.

DATA: itab_conn TYPE STANDARD TABLE OF struct_conn, wa_conn TYPE struct_conn.

Creating an Internal Table

structstruct__connconn,,

TYPE STANDARD TABLE OFTYPE STANDARD TABLE OF

structstruct__connconn..

n From Release 4.0 forward, the R/3 System has included three types of tables: Standard tables (STANDARD TABLE), sorted tables (SORTED TABLE), and hashed tables (HASHED TABLE).

n See the online documentation for information on the complete syntax of internal tables.

© SAP AG TAW12 17-7

SAP AG 2002

CARR CONN PRICE

DLDLLHLH

1699198404000402

24.500,0013.100,005.700,00

36.750,00

LH 0400 3.925,00

APPEND <wa> TO <itab>. COLLECT <wa> INTO <itab>.

<wa>

CARR CONN PRICE

DLDLLHLH

24.500,0013.100,005.700,00

36.750,00

LH 0400 3.925,00

9.625,00

Filling an Internal Table

<itab>

1699198404000402

SELECT f1 f2 f3… FROM <dbtab> INTO TABLE <itab>.

DLDLLHLH

1699198404000402

24.500,0013.100,005.700,00

36.750,00

n You can use an array fetch in a SELECT statement to fill an internal table using the syntax SELECT carrid connid price currency INTO TABLE itab_sflight.

n You can use the APPEND statement to insert table entries at the end of an internal table. The variant of the APPEND statement on the graphic is permitted only for standard or sorted tables. After an APPEND statement, the system field SY-TABIX contains the index value of the newly inserted table entry.

n You can use the COLLECT statement to create a unique or compressed set of data. The system searches the table for an existing row that matches the character field(s) in the work area. If a match is found, the numeric values in the work area are added to the existing row's values. If no matching row is found, the work area is added as a new row in the table. When the COLLECT statement is used, all the fields that are not part of the key must be numeric.

n The internal table must have at lease one character field and at least one numeric field.

© SAP AG TAW12 17-8

SAP AG 2002

SORT <itab> [BY <f1> <f2> ...][ASCENDING | DESCENDING].

LOOP AT <itab> [INTO <wa>].... ENDLOOP.

REPORT sapbc405dapd_a_internal_tables.... DATA: itab_conn TYPE STANDARD TABLE OF struct_conn,

wa_conn TYPE struct_conn.

GET spfli FIELDS carrid cityfrom cityto deptime arrtime. MOVE-CORRESPONDING spfli TO wa_conn. APPEND wa_conn TO itab_conn.

END-OF-SELECTION.cityfrom cityto carrid deptime.

WRITE: / wa_conn-cityfrom, wa_conn-cityto, wa_conn-carrid, 51 wa_conn-deptime, 65 wa_conn-arrtime.

Sorting and Processing an Internal Table

SORTSORT itabitab__connconn BYBY

LOOP AT itab_conn INTO wa_conn.

ENDLOOP.

n The SORT statement sorts the table entries in ascending order. If the table type is STANDARD or HASHED and the addition BY<f1> is missing, the keys defined for table would be used for the sort sequence. Note that table type SORTED cannot be sorted into a different sequence.

n If addition BY <f1> <f1> ... is used, then fields <f1>, <f2> ... are used as sort keys. The fields can be of any data type.

n You can use the additions ASCENDING and DESCENDING with the SORT statement to control which fields are to sort in in ascending or descending order. Ascending order is the default. For control level processing, the sort sequence must be in ascending order.

n For more information about the SORT statement, please refer to appendix documentation DAP-3. n You use the LOOP AT <itab> ... ENDLOOP keywords to process an internal table row by row. n The EXIT keyword can be used to break out of the loop processing. n After ENDLOOP, the system field SY-SUBRC indicates whether the loop was processed or not:

SY-SUBRC = 0: The loop was passed at least once. SY-SUBRC = 4: The loop was not passed because no entry was available.

© SAP AG TAW12 17-9

SAP AG 2002

AT FIRST.AT NEW <f>.AT END OF <f>.AT LAST.

[SUM.] ... ENDAT.[SUM.] ... ENDAT.[SUM.] ... ENDAT.[SUM.] ... ENDAT.

REPORT sapbc405dapd_c_itab_gr_level.TYPES: BEGIN OF struct_conn,

cityfrom LIKE spfli-cityfrom, cityto LIKE spfli-cityto, ...

END OF struct_conn.DATA: itab_conn TYPE STANDARD TABLE OF struct_conn, ...END-OF-SELECTION.

SORT itab_conn BY cityfrom cityto carrid connid fldate.LOOP AT itab_conn INTO wa_conn.

ENDLOOP.

Control Level Processing for Internal Tables

citytocitytocityfromcityfrom

AT NEW cityfrom. [SUM.] ENDAT.

AT NEW cityto. [SUM.] ENDAT.

AT END OF cityto. [SUM.] ENDAT.

n The AT events are used within a LOOP AT…ENDLOOP construct to implement control break processing.

n The statement blocks AT FIRST and AT LAST behave like first time and last time switches and execute only once.

n The statements between AT NEW <f> ... ENDAT are executed when the value of field <f> changes within the loop process and indicate the start of a control level. The statements between AT END OF <f> ... ENDAT are executed when the value of field <f> changes during the end of a control level.

n When the AT events occur, all character fields to the right of the break field are initialized with asterisks while all numeric fields are cleared. If the SUM keyword is coded, the system automatically totals all numeric fields for the current break level. After the ENDAT, all fields are repopulated with the values for the current loop pass.

© SAP AG TAW12 17-10

SAP AG 2002

REPORT ...TYPES: BEGIN OF struct,

f1 ..., f2 ..., f3 ...,

END OF struct. DATA: itab TYPE STANDARD TABLE OF struct, wa TYPE struct....SORT itab BY f1 f2.

LOOP AT itab INTO wa.AT FIRST. <Statements> ENDAT.

AT NEW f1. <Statements> ENDAT.AT NEW f2. <Statements> ENDAT.

<Single Record Processing>AT END OF f2. <Statements> ENDAT.

AT END OF f1. <Statements> ENDAT.AT LAST. <Statements> ENDAT.

ENDLOOP.

Control Level Processing Schema for Internal Tables

n To implement control level processing using an internal table, the break fields must be declared in the desired break sequence. The first break field must be the first table column and the second break field must be defined next, and so on.

n The internal table data must be sorted in ascending sequence. n The processing block between AT FIRST and ENDAT is executed before processing of the single

lines begins. The processing block AT LAST and ENDAT is executed after all single lines have been processed.

n Look closely at the control levels listed above. The AT events must be coded in the sequence shown in the graphic. Also notice that the single record processing must follow the last of the AT NEW events but before the first of the AT END OF events.

© SAP AG TAW12 17-11

SAP AG 2002

Data Formatting and Control Level Processing

OverviewOverview

Internal TablesInternal Tables

Extract DatasetsExtract Datasets

Comparison of Both TechniquesComparison of Both Techniques

© SAP AG TAW12 17-12

SAP AG 2002

FIELD-GROUPS: header, connections, flights.

header connections flights

carrid

INSERT:spfli-carrid spfli-connidsflight-fldate INTO header,

spfli-cityfrom spfli-airpfrom ... INTO connections.

connid fldate cityfrom airpfrom ...

header connections flights

EXTRACT connections.

LH 400 FRAFrankfurt

Creating an Extract Dataset

l Name field groups

n Statement: FIELD-GROUPS

w Field group HEADER must always be present

l Specify field groups

n Statement: INSERT ... INTO

l Fill extract

n Statement: EXTRACT

n Field groups are used to process large amounts of data. While the internal table control break processing is limited to the available memory on the application server, the extract dataset is processed as a sequential file on disk.

n The INSERT keyword is used to put data objects and field symbols into each of the field groups. The data objects for the field-groups must be defined as global data objects.

n If you use field symbols, you can dynamically insert data objects referred to by field symbols at runtime. Any field symbols that have not been assigned are ignored, which means no new field is inserted into the field group.

n The EXTRACT keyword places the field group and writes the field group as one record to a sequential dataset. The field group HEADER is required and is placed at the beginning of each field group to be used as sort fields. Once all the data has been processed, sort the dataset using the SORT keyword and process the extract dataset with LOOP ...ENDLOOP.

n Note that you do not code an EXTRACT for the HEADER field group. The system takes care of putting the HEADER field group at the beginning all other field groups.

© SAP AG TAW12 17-13

SAP AG 2002

REPORT sapbc405dapd_d_extracts.

* Naming field groups FIELD-GROUPS: header, connections, flights, bookings. * Specifying field groups INSERT: spfli-carrid spfli-connid

sflight-fldate INTO header, spfli-cityfrom spfli-airpfrom spfli-cityto spfli-airpto INTO connections, sflight-price sflight-paymentsum sflight-currency seatsfree INTO flights, sbook-bookid INTO bookings.

* Data retrieval GET spfli FIELDS carrid connid.

EXTRACT connections.GET sflight FIELDS fldate price ...

seatsfree = ... EXTRACT flights.

GET sbook FIELDS bookid. EXTRACT bookings.

... 00000048LH 400 12.29.02

LH 400 12.29.02 1,332.00 USD ...

LH 400 'X00' FRAFrankfurt ...

Example: Generating an Extract

INTO INTO headerheader,,

INTO INTO connectionsconnections,,

INTO INTO flightsflights,,INTO INTO bookingsbookings..

EXTRACTEXTRACT

INSERT:INSERT:

FIELDFIELD--GROUPS:GROUPS:

EXTRACTEXTRACT

EXTRACTEXTRACT

n The INSERT statement is not a declarative statement such as DATA or TYPES. As a result, the fields groups can be expanded in the START-OF-SELECTION event.

n As soon as the first dataset of a field group has been extracted with EXTRACT, that field group can no longer be expanded with INSERT.

n When the system puts the HEADER field group at the beginning of each secondary field group, the fields for which there are no values are filled with hexadecimal zeros. Since the HEADER contains the sort fields for all field groups, these hexadecimal zeros in the HEADER serve as a type of hierarchy key. The more zeros there are, the further up in the control level hierarchy you go.

© SAP AG TAW12 17-14

SAP AG 2002

AT FIRST. ...AT NEW <f>. ...AT <fg>. ... AT <fg_1> WITH <fg_2>.AT END OF <f>. CNT(<hf>) AT LAST. CNT(<hf>)

ENDAT.ENDAT.ENDAT.ENDAT.SUM(<nf>) ENDAT.SUM(<nf>) ENDAT.

SORT [BY <f1> <f2> ...][ASCENDING |DESCENDING].

LOOP. ...ENDLOOP.

Sorting and Processing an Extract

n The SORT statement sorts the extract dataset in accordance with the defined field sequence in field group HEADER. The addition BY <f1> <f2> lets you control the sequence. Each field used to sort the extract dataset must be contained in the special field group HEADER.

n Processing of an extract dataset always takes places within a LOOP. ENDLOOP. As the loop is processed, the data from the field groups are placed in the program fields with the same name.

n Control break processing is only possible on fields in the HEADER field group. Single record processing for extract datasets is performed using AT <field_group>.

n The extract dataset does not allow the use of SUM used with internal table processing. It does, however offer two options that are unique to extract datasets.

n In the AT END OF event, you can have the system count the number of entries for that control level. You can also selectively sum individual fields as well. This is the only time that a form of mathematics is done within the WRITE keyword.

n The data object you select for the CNT keyword must be an alphanumeric field in the HEADER field group. The data object you select for the SUM keyword can be a field in any of the field groups. The syntax is: WRITE: / CNT(<header_field_group_field>), SUM(<any_numeric_field_group_field>).

n SUM and CNT are only available at AT END OF or AT LAST. If you try to use the SUM keyword on its own, the program will terminate abnormally.

© SAP AG TAW12 17-15

SAP AG 2002

REPORT sapbc405dapd_d_extracts....END-OF-SELECTION.* Sorting extract data in the order of the header fields SORT.

* Control Level Processing LOOP.AT NEW spfli-connid. WRITE ... ENDAT.AT NEW sflight-fldate. WRITE ... ENDAT.

* Single record processing AT connections. WRITE ... ENDAT.AT flights WITH bookings. WRITE ... ENDAT.

AT END OF spfli-connid. ... ENDAT.ENDLOOP.

Example: Control Level Processing

SORT.SORT.

LOOP.LOOP.

AT NEWAT NEW

ATATAT END OFAT END OF

ENDAT.ENDAT.AT NEWAT NEW

ENDAT.ENDAT.ENDAT.ENDAT.

ENDAT.ENDAT.

ENDAT.ENDAT.

ATAT

ENDLOOP.ENDLOOP.

n Single record processing for extract datasets AT <field_group_1> WITH <field_group_2fg_2> allows you to process <field_group1> only if it is immediately followed by only <field_group_2>. This is very useful for header and detail processing where you do not want the header information to print unless there is supporting detail.

n Loops over an extract dataset cannot be nested. However, several consecutive loops are possible.

© SAP AG TAW12 17-16

SAP AG 2002

Using Field Symbols in Extract Datasets

FIELD-SYMBOLS: <fs1> TYPE any, <fs2> TYPE any, <fs3> TYPE any.FIELD-GROUPS: header, detail.

CASE ‘X’.WHEN p_date.

ASSIGN sflight-fldate TO <fs1>.ASSIGN sflight-planetype TO <fs2>.ASSIGN sflight-carrid TO <fs3>.

WHEN p_carrid.…..

endcase

Select sort by field

Carrier

Connection

Flight Date

Plane type

LOOP.AT NEW <fs1>.PERFORM new_fs1.

ENDAT.

AT NEW <fs2>.PERFORM new_fs2.

ENDAT.

AT detail.PERFORM write_detail.

ENDAT.

AT END OF <fs1>.ULINE.

ENDAT.ENDLOOP.SORT ASCENDING AS TEXT BY <fs1> <fs2> <fs3>.

n You can insert field symbols into your field groups instead of using data object names. This allows a single program to produce multiple different output formats.

n The steps required are quite simple: � Define as many field symbols as necessary for the processing. � Define the required field group HEADER and as many subordinate field groups as necessary. � Create a set of radio buttons on the selection screen to allow the user to determine the report

output sequence. � Evaluate the user’s selection, typically in a CASE construct, and assign data object names to the

field symbols. Note the syntax for the ASSIGN keyword. � Insert the field symbols into the appropriate field groups.

© SAP AG TAW12 17-17

SAP AG 2002

FIELD-GROUPS: header, record1, record2.

INSERT: f2 f1 INTO header,f3 f4 INTO record1,f5 INTO record2.

...END-OF-SELECTION

SORT BY f1 f2.LOOP.

AT FIRST. <statements> ENDAT.AT NEW f1. <statements> ENDAT.

AT NEW f2. <statements> ENDAT.

AT record1. <statements> ENDAT.AT record2. <statements> ENDAT.

AT END OF f2. <statements> ENDAT.AT END OF f1. <statements> ENDAT.

AT LAST. <statements> ENDAT.ENDLOOP.

Control headerprocessing

Control footerprocessing

Single recordprocessing

Schema of Control Level Processing for Extracts

n The sequence of the control level changes within the LOOP must correspond to the sort sequence. n Totals can only be calculated within control footer processing.

© SAP AG TAW12 17-18

SAP AG 2002

Data Formatting and Control Level Processing

OverviewOverview

Internal TablesInternal Tables

Extract DatasetsExtract Datasets

Comparison of Both TechniquesComparison of Both Techniques

© SAP AG TAW12 17-19

SAP AG 2002

Internal tableInternal table ExtractExtract

l All table rows have the same structure

l Static line type

l Control level processing only according to the field sequence of the line type

l Totaling (SUM) bound to high costs

l A single EXTRACT dataset

l Control level totals only in the control footer (AT END OF f, AT LAST)

l Few operations (only append, sort and sequential processing)

l Expansion of the dataset with EXTRACT after SORT or LOOP no longer possible

l Multiple different row structures are supported.

l Dynamic record types (INSERT is not a declarative statement!)

l Control level processing according to the sort sequence (independent of header sequence)

l Totaling (SUM(f)) optimized

Comparing Internal Tables and Extract Datasets

l Several internal tables

l Control level totals also in the control header (AT FIRST, AT NEW f)

l Internal table keywords insert, modify, delete, and append are permitted

l Changing internal tables always possible

n Extracts allow only EXTRACT, SORT, and sequential processing using LOOP. Once a SORT or LOOP has occurred, the intermediate dataset structure is frozen and cannot be expanded with EXTRACT. Operations that insert into or delete from EXTRACT datasets are not supported.

n Extracts allow for several different row structures with fields that can be set dynamically. Internal tables have a single, statically defined line type.

n Internal tables use the sequence of table fields according to the declaration for the hierarchy of the control level. The control level structure for internal tables is therefore static, and is independent of which criteria were used to sort the internal table. Extracts do not depend on the field sequence for control level processing: A re-sort or a completely different control level process can take place. The control level structure for extract datasets is dynamic. It corresponds to the sort key of the extract dataset. The sort key is the sequence of fields from the field group HEADER, and is used to sort the extract dataset.

n Extracts rely on the compiler to determine which combinations of group levels and cumulating field the control level totals desire. The desired control level totals are determined by the processing of LOOP ... ENDLOOP blocks. Internal tables build the control level total with the SUM statement. This procedure leads to high resource depletion for totaling control levels in internal tables.

© SAP AG TAW12 17-20

SAP AG 2002

Data Formatting and Control Level Processing: Unit Summary

You are now able to:

l Format data with internal tables.

l Use control level processing with internal tables and extract datasets.

© SAP AG TAW12 17-21

Data Formatting and Control Level Processing Exercises

Unit: Data Formatting and Control Level Processing

Topic: Internal Tables

When you have completed these exercises, you will be able to:

• Implement control level processing with internal tables

1-1 Copy or enhance your program Z##GDA1_..., or copy the sample solution, SAPBC405_GDAS_1, to program Z##DAP1_... . Sample solution for exercise: SAPBC405_DAPS_1.

Carry out control level processing for CITYFROM, CITYTO, CARRID, and CONNID. Create a list like the one in the template.

1-1-1 Create a line type in the TOP include (TYPES statement). Declare the internal table and the work area in accordance with the line type. You should include the following fields:

CARRID, CONNID, FLDATE, PRICE, CURRENCY, CITYFROM, COUNTRYFR, CITYTO, COUNTRYTO, SEATSMAX, SEATSOCC.

Note: The control level hierarchy for an internal table is established by your line structure.

1-1-2 Sort the internal table in accordance with the requested control level processing (event: END-OF-SELECTION).

1-2 Implement the control level processing in your output routine.

1-2-1 Display each new departure city on a separate page and with intensive display in color COL_GROUP in the list.

1-2-2 Display the city and airport for each new arrival city with a less intensive display in color COL_GROUP.

1-2-3 Ensure that the icon ICON_BW_GIS (for international flights), the airline, and the flight number are displayed as required during single-record processing. Display the key fields in color COL_KEY; they should remain as hard lead columns. Display the flight date, the price, the currency, the maximum number of seats, and the number occupied in color COL_NORMAL in the list with a less intensive display.

1-2-4 At the end of each flight connection, the totals for the maximum number of seats and the number occupied should be displayed in color COL_TOTAL without intensive display.

1-2-5 A solid line should appear on the list before the departure location changes.

© SAP AG TAW12 17-22

1-2-6 Draw a frame around the list (sy-vline).

1-2-7 Modify the column headers to fit the new list output (see the template). Use text elements to allow your texts to be translated.

Template:

Flight data

Departure city Arrival city Flight Date Price Max. Occ.

FRANKFURT NEW YORK @ LH 0400 09.07.1999 1,332.00 EUR 280 173 @ LH 0400 11.29.1999 1,332.00 EUR 280 156 @ LH 0400 12.02.1999 1,332.00 EUR 280 24 @ LH 0400 12.09.1999 1,332.00 EUR 280 198 @ LH 0400 12.29.1999 1,332.00 EUR 280 277 Total 1400 828 @ LH 0402 09.29.1999 1,332.00 EUR 280 210 @ LH 0402 12.28.1999 1,332.00 EUR 280 280 @ LH 0402 01.02.2000 1,332.00 EUR 280 280 @ LH 0402 01.05.2000 1,332.00 EUR 280 198 @ LH 0402 02.08.2000 1,332.00 EUR 280 11 Total 1400 979

@ = ICON_BW_GIS

© SAP AG TAW12 17-23

Exercises

Unit: Data Formatting and Control Level Processing

Topic: Extracts

When you have completed these exercises, you will be able to:

• Name field groups.

• Define field groups.

• Create extracts.

• Perform control level processing with extracts.

2-1 Copy or enhance your program Z##LDB2_..., or copy the sample solution, SAPBC405_LDBS_2, to program Z##DAP2_... Sample solution for exercise: SAPBC405_DAPS_2.

2-1-1 Deactivate the events GET … LATE.

2-1-2 Define the following field groups in the TOP to include:

HEADER

CONNECTIONS

FLIGHTS

BOOKINGS

2-1-3 Assign the following fields to the field groups:

HEADER: spfli-carrid, spfli-connid, sflight-fldate, sbook-bookid, sbook-customid

CONNECTIONS: spfli-cityfrom, spfli-airpfrom, spfli-cityto, spfli-airpto

FLIGHTS: sflight-price, sflight-currency, sflight-planetype, sflight-seatsmax, sflight-seatsocc, free_seats

BOOKINGS: sbook-bookid, sbook-customid, sbook-smoker, sbook-luggweight, sbook-wunit.

2-1-4 Fill the extract dataset for the GET events.

2-1-5 Sort the extract according to the sequence of field group HEADER.

2-1-6 Start control level processing and create a list with the following structure:

Line 1: SPFLI-CARRID, SPFLI-CONNID

Line 2: SFLIGHT-FLDATE

Line 3: SPFLI-CITYFROM, SPFLI-AIRPFROM, SPFLI-CITYTO, SPFLI-AIRPTO

© SAP AG TAW12 17-24

Line 4: SFLIGHT-PRICE, SFLIGHT-CURRENCY, SFLIGHT- PLANETYPE, SFLIGHT-SEATSMAX, SFLIGHT-SEATSOCC, FREE_SEATS

Line 5: SBOOK-BOOKID, SBOOK-CUSTOMID, SBOOK-SMOKER, BOOK-LUGGWEIGHT, SBOOK-WUNIT.

Only output line 3 if line 4 is also output.

Only output line 4 if line 5 is also output.

2-1-7 The list should also include the number of total bookings and the total weight of the luggage for each flight date in one line.

2-2 Formatting the list

2-2-1 The price and luggage weight should be output with correct format for the respective units.

2-2-2 Display each flight on a new page.

2-2-3 Display a solid line before and after the number of bookings and the total weight.

2-2-4 Use the following control structures and colors:

AT NEW spfli-connid, COL_GROUP INTENSIFIED ON

AT NEW sflight-fldate, COL_HEADING INTENSIFIED ON

AT flights WITH bookings, COL_NORMAL INTENSIFIED ON

AT bookings, COL_NORMAL INTENSIFIED OFF

AT END OF sflight-fldate, COL_TOTAL INTENSIFIED ON

2-2-5 Position the control levels in the list in such a way that the hierarchy is apparent. For example, line 1 begins further to the left than line 2, and so on. Draw a frame around the list. Maintain the column headers (standard list header).

© SAP AG TAW12 17-25

Exercises

Unit: Data Formatting and Control Level Processing

Topic: Extract Dataset with Field Symbols

When you have completed these exercises, you will be able to:

• Implement control level processing with an extract dataset using field-symbols.

3-1 Create a new program Z##LDB3 to create an extract dataset using field symbols. Data should be read from the transparent table SFLIGHT. This report should create a different output depending on a radio button group on the report selection screen.

3-1-1 Define an extract dataset with two field groups: HEADER and DETAIL.

3-1-2 Define four field symbols as TYPE ANY.

3-1-3 Create a radio button group on the report selection screen that has four buttons: Carrier ID, Connection, Flight Date, and Plane type.

3-1-4 Require the user to enter a valid carrier ID when the report executes.

3-1-5 Depending on the radio button selected, the report should be sorted in one of the following four sequences:

3-1-5-1 Radio button 1: Carrier ID, Connection, Flight Date, Plane type

3-1-5-2 Radio button 2: Connection, Flight Date, Plane type Carrier ID

3-1-5-3 Radio button 3: Flight Date, Plane type, Carrier ID, Connection

3-1-5-4 Radio button 4: Plane type, Carrier ID, Connection, Flight Date.

3-1-6 Insert the field symbols into the HEADER group and the DETAIL group

3-1-7 Read the found columns needed for the report in a SELECT…ENDSELECT loop. The EXTRACT should be contained inside the loop.

3-1-8 Sort the extract dataset and LOOP it to create the report.

3-1-9 Include the following breaks:

AT NEW <fs1>.

AT detail.

AT END OF <fs1>.

© SAP AG TAW12 17-26

Data Formatting and Control Level Processing Solutions

Unit: Data Formatting and Control Level Processing

Topic: Internal Tables

*&---------------------------------------------------------------------*

*& Report SAPBC405_DAPS_1 *

*& *

*&---------------------------------------------------------------------*

*& Solution; Exercise 1; Control level processing

With internal table

*& *

*&---------------------------------------------------------------------*

INCLUDE bc405_daps_1top.

*&---------------------------------------------------------------------*

*& Event TOP-OF-PAGE

*&---------------------------------------------------------------------*

TOP-OF-PAGE.

* Title

FORMAT COLOR COL_HEADING INTENSIFIED ON.

ULINE.

WRITE: / sy-vline,

'Flight data'(001),

AT line_size sy-vline.

ULINE.

* Column header

FORMAT COLOR COL_HEADING INTENSIFIED OFF.

WRITE: sy-vline, 'Departure location'(004), AT line_size sy-vline.

WRITE: sy-vline, 'Arrival location'(004), AT line_size sy-vline.

WRITE: sy-vline, AT pos_c1 'Flight'(002).

* Fix left scroll boundary

SET LEFT SCROLL-BOUNDARY.

WRITE: 'Date'(003),

© SAP AG TAW12 17-27

AT pos_c3 'Price'(006),

AT pos_c4 'Max.'(008),

AT pos_c5 'Occ.'(009),

AT line_size sy-vline.

ULINE.

*&---------------------------------------------------------------------*

*& Event INITIALIZATION

*&---------------------------------------------------------------------*

INITIALIZATION. " OPTIONAL

* Initialize select-options for CARRID

MOVE: 'AA' TO so_car-low,

'QF' TO so_car-high,

'BT' TO so_car-option,

'I' TO so_car-sign.

APPEND so_car.

CLEAR so_car.

MOVE: 'AZ' TO so_car-low,

'EQ' TO so_car-option,

'E' TO so_car-sign.

APPEND so_car.

CLEAR so_car.

*&---------------------------------------------------------------------*

*& Event AT SELECTION-SCREEN ON BLOCK PARAM

*&---------------------------------------------------------------------*

AT SELECTION-SCREEN ON BLOCK param. " OPTIONAL

* check country for national flights is not empty

CHECK national = 'X' AND country = space.

MESSAGE e003(bc405).

*&---------------------------------------------------------------------*

*& Event START-OF-SELECTION

*&---------------------------------------------------------------------*

START-OF-SELECTION.

* Checking the output parameters

CASE mark.

WHEN all.

© SAP AG TAW12 17-28

* Radiobutton ALL is marked

SELECT * FROM spfli INNER JOIN sflight

ON spfli~carrid = sflight~carrid

AND spfli~connid = sflight~connid

INTO CORRESPONDING FIELDS OF TABLE it_flights

WHERE spfli~carrid IN so_car

AND spfli~connid IN so_con

AND sflight~fldate IN so_fdt.

WHEN national.

* Radiobutton NATIONAL is marked

SELECT * FROM spfli INNER JOIN sflight

ON spfli~carrid = sflight~carrid

AND spfli~connid = sflight~connid

INTO CORRESPONDING FIELDS OF TABLE it_flights

WHERE spfli~carrid IN so_car

AND spfli~connid IN so_con

AND sflight~fldate IN so_fdt

AND spfli~countryfr = spfli~countryto

AND spfli~countryfr = country.

WHEN internat.

* Radiobutton INTERNAT is marked

SELECT * FROM spfli INNER JOIN sflight

ON spfli~carrid = sflight~carrid

AND spfli~connid = sflight~connid

INTO CORRESPONDING FIELDS OF TABLE it_flights

WHERE spfli~carrid IN so_car

AND spfli~connid IN so_con

AND sflight~fldate IN so_fdt

AND spfli~countryfr NE spfli~countryto.

ENDCASE.

* Additional solution: dynamical WHERE condition

* PERFORM get_data.

*&---------------------------------------------------------------------*

*& Event END-OF-SELECTION

*&---------------------------------------------------------------------*

© SAP AG TAW12 17-29

END-OF-SELECTION.

*SORT it_flights BY carrid connid fldate.

* Control Level Processing: the internal table has to be sorted

SORT it_flights BY cityfrom cityto carrid connid.

* Data output

PERFORM data_output.

*&---------------------------------------------------------------------*

*& Form DATA_OUTPUT

*&---------------------------------------------------------------------*

* List output of flight data

*----------------------------------------------------------------------*

FORM data_output.

* Loop at the internal table for writing data

LOOP AT it_flights INTO wa_flights.

* Group Level: CITYFROM

AT NEW cityfrom.

NEW-PAGE.

FORMAT COLOR COL_GROUP INTENSIFIED ON.

WRITE: / sy-vline, wa_flights-cityfrom,

AT line_size sy-vline.

FORMAT RESET.

ENDAT.

* Group Level: CITYTO

AT NEW cityto.

FORMAT COLOR COL_GROUP INTENSIFIED OFF.

WRITE: / sy-vline, wa_flights-cityto,

AT line_size sy-vline.

FORMAT RESET.

ENDAT.

* Single Record Processing

* Mark international flights

FORMAT COLOR COL_KEY INTENSIFIED ON.

IF wa_flights-countryfr EQ wa_flights-countryto.

WRITE: / sy-vline, icon_space AS ICON CENTERED.

© SAP AG TAW12 17-30

ELSE.

WRITE: / sy-vline, icon_bw_gis AS ICON CENTERED.

ENDIF.

* Data output

WRITE: wa_flights-carrid,

wa_flights-connid.

FORMAT COLOR COL_NORMAL INTENSIFIED OFF.

WRITE: wa_flights-fldate,

wa_flights-price CURRENCY wa_flights-currency,

wa_flights-currency,

wa_flights-seatsmax,

wa_flights-seatsocc,

AT line_size sy-vline.

FORMAT RESET.

* Group Level: CONNID

AT END OF connid.

SUM.

FORMAT COLOR COL_TOTAL.

WRITE: / sy-vline,

'Total'(007),

wa_flights-seatsmax UNDER wa_flights-seatsmax,

wa_flights-seatsocc UNDER wa_flights-seatsocc,

AT line_size sy-vline.

FORMAT RESET.

ENDAT.

* Group Level: CITYFROM

AT END OF cityfrom.

ULINE.

ENDAT.

ENDLOOP.

ENDFORM. " DATA_OUTPUT

*&---------------------------------------------------------------------*

*& Include BC405_DAPS_1TOP *

*& *

*&---------------------------------------------------------------------*

REPORT bc405_daps_1top LINE-SIZE 100 NO STANDARD PAGE HEADING.

© SAP AG TAW12 17-31

* Include for using icons

INCLUDE <icon>.

* Linetype of internal table

TYPES: BEGIN OF linetype,

cityfrom LIKE spfli-cityfrom,

cityto LIKE spfli-cityto,

carrid LIKE spfli-carrid,

connid LIKE spfli-connid,

countryfr like spfli-countryfr,

countryto like spfli-countryto,

fldate LIKE sflight-fldate,

price LIKE sflight-price,

currency LIKE sflight-currency,

seatsmax LIKE sflight-seatsmax,

seatsocc LIKE sflight-seatsocc,

end of linetype.

* Constants for writing position

CONSTANTS: pos_c1 TYPE i VALUE 6,

pos_c3 TYPE i VALUE 30,

pos_c4 TYPE i VALUE 58,

pos_c5 TYPE i VALUE 68,

line_size TYPE i VALUE 100.

* Constant for CASE statement

CONSTANTS mark VALUE 'X'.

* Internal table like DDIC view DV_FLIGHTS

* DATA: it_flights LIKE TABLE OF dv_flights,

* wa_flights LIKE dv_flights.

* Internal table type linetype

DATA: it_flights TYPE STANDARD TABLE OF linetype,

wa_flights TYPE linetype.

* Selections for connections

SELECTION-SCREEN BEGIN OF BLOCK conn WITH FRAME TITLE text-tl1.

SELECT-OPTIONS: so_car FOR wa_flights-carrid,

so_con FOR wa_flights-connid.

SELECTION-SCREEN END OF BLOCK conn.

© SAP AG TAW12 17-32

* Selections for flights

SELECTION-SCREEN BEGIN OF BLOCK flight WITH FRAME TITLE text-tl2.

SELECT-OPTIONS so_fdt FOR wa_flights-fldate NO-EXTENSION.

SELECTION-SCREEN END OF BLOCK flight.

* Output parameter

SELECTION-SCREEN BEGIN OF BLOCK param

WITH FRAME TITLE text-tl3.

SELECTION-SCREEN BEGIN OF BLOCK radio WITH FRAME.

PARAMETERS: all RADIOBUTTON GROUP rbg1,

national RADIOBUTTON GROUP rbg1,

internat RADIOBUTTON GROUP rbg1 DEFAULT 'X'.

SELECTION-SCREEN END OF BLOCK radio.

PARAMETERS country LIKE wa_flights-countryfr.

SELECTION-SCREEN END OF BLOCK param.

© SAP AG TAW12 17-33

Solutions

Unit: Data Formatting and Control Level Processing

Topic: Internal Table

*&---------------------------------------------------------------------*

*& Report SAPBC405_DAPS_1 *

*& *

*&---------------------------------------------------------------------*

*& Solution; Exercise 1; Control level processing

With internal table

*& *

*&---------------------------------------------------------------------*

INCLUDE bc405_daps_1top.

*&---------------------------------------------------------------------*

*& Event TOP-OF-PAGE

*&---------------------------------------------------------------------*

TOP-OF-PAGE.

* Title

FORMAT COLOR COL_HEADING INTENSIFIED ON.

ULINE.

WRITE: / sy-vline,

'Flight data'(001),

AT line_size sy-vline.

ULINE.

* Column header

FORMAT COLOR COL_HEADING INTENSIFIED OFF.

WRITE: sy-vline, 'Departure location'(004), AT line_size sy-vline.

WRITE: sy-vline, 'Arrival location'(004), AT line_size sy-vline.

© SAP AG TAW12 17-34

WRITE: sy-vline, AT pos_c1 'Flight'(002).

* Fix left scroll boundary

SET LEFT SCROLL-BOUNDARY.

WRITE: 'Date'(003),

AT pos_c3 'Price'(006),

AT pos_c4 'Max.'(008),

AT pos_c5 'Occ.'(009),

AT line_size sy-vline.

ULINE.

*&---------------------------------------------------------------------*

*& Event INITIALIZATION

*&---------------------------------------------------------------------*

INITIALIZATION. " OPTIONAL

* Initialize select-options for CARRID

MOVE: 'AA' TO so_car-low,

'QF' TO so_car-high,

'BT' TO so_car-option,

'I' TO so_car-sign.

APPEND so_car.

CLEAR so_car.

MOVE: 'AZ' TO so_car-low,

'EQ' TO so_car-option,

'E' TO so_car-sign.

APPEND so_car.

CLEAR so_car.

*&---------------------------------------------------------------------*

*& Event AT SELECTION-SCREEN ON BLOCK PARAM

*&---------------------------------------------------------------------*

AT SELECTION-SCREEN ON BLOCK param. " OPTIONAL

* check country for national flights is not empty

CHECK national = 'X' AND country = space.

© SAP AG TAW12 17-35

MESSAGE e003(bc405).

*&---------------------------------------------------------------------*

*& Event START-OF-SELECTION

*&---------------------------------------------------------------------*

START-OF-SELECTION.

* Checking the output parameters

CASE mark.

WHEN all.

* Radiobutton ALL is marked

SELECT * FROM spfli INNER JOIN sflight

ON spfli~carrid = sflight~carrid

AND spfli~connid = sflight~connid

INTO CORRESPONDING FIELDS OF TABLE it_flights

WHERE spfli~carrid IN so_car

AND spfli~connid IN so_con

AND sflight~fldate IN so_fdt.

WHEN national.

* Radiobutton NATIONAL is marked

SELECT * FROM spfli INNER JOIN sflight

ON spfli~carrid = sflight~carrid

AND spfli~connid = sflight~connid

INTO CORRESPONDING FIELDS OF TABLE it_flights

WHERE spfli~carrid IN so_car

AND spfli~connid IN so_con

AND sflight~fldate IN so_fdt

AND spfli~countryfr = spfli~countryto

AND spfli~countryfr = country.

WHEN internat.

* Radiobutton INTERNAT is marked

SELECT * FROM spfli INNER JOIN sflight

ON spfli~carrid = sflight~carrid

© SAP AG TAW12 17-36

AND spfli~connid = sflight~connid

INTO CORRESPONDING FIELDS OF TABLE it_flights

WHERE spfli~carrid IN so_car

AND spfli~connid IN so_con

AND sflight~fldate IN so_fdt

AND spfli~countryfr NE spfli~countryto.

ENDCASE.

* Additional solution: dynamical WHERE condition

* PERFORM get_data.

*&---------------------------------------------------------------------*

*& Event END-OF-SELECTION

*&---------------------------------------------------------------------*

END-OF-SELECTION.

*SORT it_flights BY carrid connid fldate.

* Control Level Processing: the internal table has to be sorted

SORT it_flights BY cityfrom cityto carrid connid.

* Data output

PERFORM data_output.

*&---------------------------------------------------------------------*

*& Form DATA_OUTPUT

*&---------------------------------------------------------------------*

* List output of flight data

*----------------------------------------------------------------------*

FORM data_output.

* Loop at the internal table for writing data

LOOP AT it_flights INTO wa_flights.

* Group Level: CITYFROM

AT NEW cityfrom.

© SAP AG TAW12 17-37

NEW-PAGE.

FORMAT COLOR COL_GROUP INTENSIFIED ON.

WRITE: / sy-vline, wa_flights-cityfrom,

AT line_size sy-vline.

FORMAT RESET.

ENDAT.

* Group Level: CITYTO

AT NEW cityto.

FORMAT COLOR COL_GROUP INTENSIFIED OFF.

WRITE: / sy-vline, wa_flights-cityto,

AT line_size sy-vline.

FORMAT RESET.

ENDAT.

* Single Record Processing

* Mark international flights

FORMAT COLOR COL_KEY INTENSIFIED ON.

IF wa_flights-countryfr EQ wa_flights-countryto.

WRITE: / sy-vline, icon_space AS ICON CENTERED.

ELSE.

WRITE: / sy-vline, icon_bw_gis AS ICON CENTERED.

ENDIF.

* Data output

WRITE: wa_flights-carrid,

wa_flights-connid.

FORMAT COLOR COL_NORMAL INTENSIFIED OFF.

WRITE: wa_flights-fldate,

wa_flights-price CURRENCY wa_flights-currency,

wa_flights-currency,

wa_flights-seatsmax,

wa_flights-seatsocc,

AT line_size sy-vline.

FORMAT RESET.

* Group Level: CONNID

AT END OF connid.

© SAP AG TAW12 17-38

SUM.

FORMAT COLOR COL_TOTAL.

WRITE: / sy-vline,

'Total'(007),

wa_flights-seatsmax UNDER wa_flights-seatsmax,

wa_flights-seatsocc UNDER wa_flights-seatsocc,

AT line_size sy-vline.

FORMAT RESET.

ENDAT.

* Group Level: CITYFROM

AT END OF cityfrom.

ULINE.

ENDAT.

ENDLOOP.

ENDFORM. " DATA_OUTPUT

*&---------------------------------------------------------------------*

*& Include BC405_DAPS_1TOP *

*& *

*&---------------------------------------------------------------------*

REPORT bc405_daps_1top LINE-SIZE 100 NO STANDARD PAGE HEADING.

* Include for using icons

INCLUDE <icon>.

* Linetype of internal table

TYPES: BEGIN OF linetype,

cityfrom LIKE spfli-cityfrom,

cityto LIKE spfli-cityto,

carrid LIKE spfli-carrid,

connid LIKE spfli-connid,

countryfr like spfli-countryfr,

countryto like spfli-countryto,

© SAP AG TAW12 17-39

fldate LIKE sflight-fldate,

price LIKE sflight-price,

currency LIKE sflight-currency,

seatsmax LIKE sflight-seatsmax,

seatsocc LIKE sflight-seatsocc,

end of linetype.

* Constants for writing position

CONSTANTS: pos_c1 TYPE i VALUE 6,

pos_c3 TYPE i VALUE 30,

pos_c4 TYPE i VALUE 58,

pos_c5 TYPE i VALUE 68,

line_size TYPE i VALUE 100.

* Constant for CASE statement

CONSTANTS mark VALUE 'X'.

* Internal table like DDIC view DV_FLIGHTS

* DATA: it_flights LIKE TABLE OF dv_flights,

* wa_flights LIKE dv_flights.

* Internal table type linetype

DATA: it_flights TYPE STANDARD TABLE OF linetype,

wa_flights TYPE linetype.

* Selections for connections

SELECTION-SCREEN BEGIN OF BLOCK conn WITH FRAME TITLE text-tl1.

SELECT-OPTIONS: so_car FOR wa_flights-carrid,

so_con FOR wa_flights-connid.

SELECTION-SCREEN END OF BLOCK conn.

* Selections for flights

SELECTION-SCREEN BEGIN OF BLOCK flight WITH FRAME TITLE text-tl2.

SELECT-OPTIONS so_fdt FOR wa_flights-fldate NO-EXTENSION.

SELECTION-SCREEN END OF BLOCK flight.

* Output parameter

© SAP AG TAW12 17-40

SELECTION-SCREEN BEGIN OF BLOCK param

WITH FRAME TITLE text-tl3.

SELECTION-SCREEN BEGIN OF BLOCK radio WITH FRAME.

PARAMETERS: all RADIOBUTTON GROUP rbg1,

national RADIOBUTTON GROUP rbg1,

internat RADIOBUTTON GROUP rbg1 DEFAULT 'X'.

SELECTION-SCREEN END OF BLOCK radio.

PARAMETERS country LIKE wa_flights-countryfr.

SELECTION-SCREEN END OF BLOCK param.

© SAP AG TAW12 17-41

Solutions

Unit: Data Formatting and Control Level Processing

Topic: Extracts

*&--------------------------------------------------------- -----------*

*& Report SAPBC405_DAPS_2 *

*& *

*&---------------------------------------------------------------------*

*& *

*& *

*&---------------------------------------------------------------------*

INCLUDE bc405_daps_2top.

*&---------------------------------------------------------------------*

*& Event GET SPFLI

*&---------------------------------------------------------------------*

GET spfli.

* Save field group: connections

EXTRACT connections.

*&---------------------------------------------------------------------*

*& Event GET SFLIGHT

*&---------------------------------------------------------------------*

GET sflight.

* Calculate free seats

free_seats = sflight-seatsmax - sflight-seatsocc.

* Save field group: flights

EXTRACT flights.

© SAP AG TAW12 17-42

*&---------------------------------------------------------------------*

*& Event GET SBOOK

*&---------------------------------------------------------------------*

GET sbook.

* Check select-option

CHECK so_odat.

* Save field group: bookings

EXTRACT bookings.

*&---------------------------------------------------------------------*

*& Event GET SPFLI LATE

*&---------------------------------------------------------------------*

*GET spfli LATE.

* ULINE.

* NEW-PAGE.

*&---------------------------------------------------------------------*

*& Event GET SFLIGHT LATE

*&---------------------------------------------------------------------*

*GET sflight LATE.

* ULINE.

*&---------------------------------------------------------------------*

*& Event END-OF-SELECTION

*&---------------------------------------------------------------------*

END-OF-SELECTION.

* Sorting extract data according to the header fields

SORT.

* Control level processing

LOOP.

AT NEW spfli-connid.

FORMAT COLOR COL_GROUP INTENSIFIED ON.

WRITE: / sy-vline,

spfli-carrid,

© SAP AG TAW12 17-43

spfli-connid,

AT line_size sy-vline.

ENDAT.

AT NEW sflight-fldate.

FORMAT COLOR COL_HEADING INTENSIFIED ON.

WRITE: / sy-vline,

AT pos_lev2 sflight-fldate,

AT line_size sy-vline.

ENDAT.

* Single record processing

AT connections WITH flights.

FORMAT COLOR COL_HEADING INTENSIFIED OFF.

WRITE: / sy-vline,

spfli-cityfrom,

spfli-airpfrom,

spfli-cityto,

spfli-airpto, AT line_size sy-vline.

ENDAT.

AT flights WITH bookings.

FORMAT COLOR COL_NORMAL INTENSIFIED ON.

WRITE: / sy-vline,

sflight-price CURRENCY sflight-currency,

sflight-currency,

sflight-planetype,

sflight-seatsmax,

sflight-seatsocc,

free_seats, AT line_size sy-vline.

ENDAT.

AT bookings.

FORMAT COLOR COL_NORMAL INTENSIFIED OFF.

WRITE: / sy-vline,

AT pos_lev3 sbook-bookid,

sbook-customid,

© SAP AG TAW12 17-44

sbook-smoker,

sbook-luggweight UNIT sbook-wunit,

sbook-wunit, AT line_size sy-vline.

ENDAT.

* Control level processing with CNT and SUM

AT END OF sflight-fldate.

FORMAT COLOR COL_TOTAL INTENSIFIED ON.

ULINE.

WRITE: sy-vline,

'Totals:'(001),

cnt(sbook-bookid) UNDER sbook-bookid,

sum(sbook-luggweight) UNIT sbook-wunit

UNDER sbook-luggweight,

sbook-wunit,

AT line_size sy-vline.

ULINE.

ENDAT.

ENDLOOP.

*&---------------------------------------------------------------------*

*& Include BC405_DAPS_2TOP

*

*& *

*&---------------------------------------------------------------------*

REPORT bc405_daps_2top LINE-SIZE 83.

* Used nodes of the structure of the logical database F1S

NODES: spfli, sflight, sbook.

* Additional selections

SELECTION-SCREEN BEGIN OF BLOCK order WITH FRAME.

SELECT-OPTIONS: so_odat FOR sbook-order_date.

SELECTION-SCREEN END OF BLOCK order.

© SAP AG TAW12 17-45

* Variables

DATA: free_seats LIKE sflight-seatsocc.

* Constants

CONSTANTS: line_size LIKE sy-linsz VALUE 83,

pos_lev2 TYPE i VALUE 10,

pos_lev3 TYPE i VALUE 20.

* Field groups

FIELD-GROUPS: header, " Group Level and sorting fields

connections, " Fields of SPFLI

flights, " Fields of SFLIGHT

bookings. " Fields of SBOOK

* Fixing of field groups

INSERT: spfli-carrid

spfli-connid

sflight-fldate

sbook-bookid

sbook-customid INTO header,

spfli-cityfrom

spfli-airpfrom

spfli-cityto

spfli-airpto INTO connections,

sflight-price

sflight-currency

sflight-planetype

sflight-seatsmax

sflight-seatsocc

free_seats INTO flights,

sbook-bookid

sbook-customid

sbook-smoker

sbook-luggweight

sbook-wunit INTO bookings.

© SAP AG TAW12 17-46

© SAP AG TAW12 17-47

Solutions

Unit: Data Formatting and Control Level Processing

Topic: Internal Tables

*&-----------------------------------------------------------------*

*& Report ZEXTRACT_DATASET_FIELD_SYMBOLS *

*& *

*&------------------------------------------------------------------*

*& *

*& *

*&------------------------------------------------------------------*

REPORT zextract_dataset_field_symbols.

*

TABLES: sflight.

*

* Zebra striping

DATA div_mod_2_remainder TYPE i.

DATA zebra_stripe_counter TYPE i.

DATA line_size LIKE sy-linsz.

*

FIELD-GROUPS: header,

detail.

*

FIELD-SYMBOLS: <fs1> TYPE ANY,

<fs2> TYPE ANY,

<fs3> TYPE ANY,

<fs4> TYPE ANY.

*********************************************************************

SELECTION-SCREEN:BEGIN OF BLOCK b01 WITH FRAME TITLE b01, “#EC NEEDED

SKIP,

BEGIN OF BLOCK b02 WITH FRAME TITLE b02. “#EC NEEDED

*

SELECTION-SCREEN: BEGIN OF LINE,

COMMENT 1(30) r01,

POSITION POS_LOW.

PARAMETERS: p_radio1 RADIOBUTTON GROUP rad1. "Carrier ID

© SAP AG TAW12 17-48

SELECTION-SCREEN: END OF LINE.

*********************************************************************

SELECTION-SCREEN: BEGIN OF LINE,

COMMENT 1(30) r02,

POSITION POS_LOW.

PARAMETERS: p_radio2 RADIOBUTTON GROUP rad1. "Connection

SELECTION-SCREEN: END OF LINE.

*********************************************************************

SELECTION-SCREEN: BEGIN OF LINE,

COMMENT 1(30) r03,

POSITION POS_LOW.

PARAMETERS: p_radio3 RADIOBUTTON GROUP rad1. "Flight date

SELECTION-SCREEN: END OF LINE.

*********************************************************************

SELECTION-SCREEN: BEGIN OF LINE,

COMMENT 1(30) r04,

POSITION POS_LOW.

PARAMETERS: p_radio4 RADIOBUTTON GROUP rad1. "Plane type date

SELECTION-SCREEN: END OF LINE.

*********************************************************************

SELECTION-SCREEN: END OF BLOCK b02.

SELECTION-SCREEN: END OF BLOCK b01.

*

INITIALIZATION.

b01 = 'Extract Dataset using FIELD-SYMBOLS'(b01).

b02 = 'Select the high order sort field'(b02).

r01 = 'Carrier ID'(r01).

r02 = 'Connection'(r02).

r03 = 'Flight Date'(r03).

r04 = 'Plane type'(r04).

*

START-OF-SELECTION.

PERFORM set_header_field.

PERFORM set_detail_fields.

PERFORM extract_the_data.

*

END-OF-SELECTION.

PERFORM sort_the_data.

PERFORM reset_the_line_size.

*********************************************************************

LOOP.

AT NEW <fs1>.

© SAP AG TAW12 17-49

PERFORM new_fs1.

CLEAR zebra_stripe_counter.

ENDAT.

AT detail.

PERFORM write_detail.

ENDAT.

AT END OF <fs1>.

ULINE.

ENDAT.

ENDLOOP.

TOP-OF-PAGE.

FORMAT COLOR COL_HEADING.

CASE 'X'.

WHEN p_radio1.

WRITE: AT (sy-linsz)'ORDER BY CARRIER ID'(h01) CENTERED NO-GAP.

WHEN p_radio2.

WRITE: AT (sy-linsz)'ORDER BY CONNECTION'(h02) CENTERED NO-GAP.

WHEN p_radio3.

WRITE: AT (sy-linsz)'ORDER BY FLIGHT DATE'(h03)CENTERED NO-GAP.

WHEN p_radio4.

WRITE: AT (sy-linsz)'ORDER BY PLANE TYPE'(h04) CENTERED NO-GAP.

ENDCASE.

WRITE: 1 sy-vline NO-GAP,

AT sy-linsz sy-vline NO-GAP.

ULINE.

FORMAT COLOR OFF.

*&------------------------------------------------------------------*

*& Form SET_HEADER_FIELD

*&------------------------------------------------------------------*

* text

*-------------------------------------------------------------------*

* --> p1 text

* <-- p2 text

*-------------------------------------------------------------------*

FORM set_header_field.

CASE 'X'.

*********************************************************************

WHEN p_radio1.

ASSIGN sflight-carrid TO <fs1>.

© SAP AG TAW12 17-50

ASSIGN sflight-connid TO <fs2>.

ASSIGN sflight-fldate TO <fs3>.

ASSIGN sflight-planetype TO <fs4>.

line_size = strlen( <fs2> )

+ STRLEN( <fs3> )

+ STRLEN( <fs4> )

+ 20.

*********************************************************************

WHEN p_radio2.

ASSIGN sflight-connid TO <fs1>.

ASSIGN sflight-fldate TO <fs2>.

ASSIGN sflight-planetype TO <fs3>.

ASSIGN sflight-carrid TO <fs4>.

line_size = strlen( <fs2> )

+ STRLEN( <fs3> )

+ STRLEN( <fs4> )

+ 23.

********************************************************************

WHEN p_radio3.

ASSIGN sflight-fldate TO <fs1>.

ASSIGN sflight-planetype TO <fs2>.

ASSIGN sflight-carrid TO <fs3>.

ASSIGN sflight-connid TO <fs4>.

line_size = strlen( <fs2> )

+ STRLEN( <fs3> )

+ STRLEN( <fs4> )

+ 21.

*********************************************************************

WHEN p_radio4.

ASSIGN sflight-planetype TO <fs1>.

ASSIGN sflight-carrid TO <fs2>.

ASSIGN sflight-connid TO <fs3>.

ASSIGN sflight-fldate TO <fs4>.

line_size = strlen( <fs2> )

+ STRLEN( <fs3> )

+ STRLEN( <fs4> )

+ 13.

ENDCASE.

INSERT: <fs1>

<fs2>

<fs3>

© SAP AG TAW12 17-51

<fs4> INTO header.

ENDFORM. " SET_HEADER_FIELD

*&------------------------------------------------------------------*

*& Form SET_DETAIL_FIELDS

*&------------------------------------------------------------------*

* text

*-------------------------------------------------------------------*

* --> p1 text

* <-- p2 text

*-------------------------------------------------------------------*

FORM set_detail_fields.

INSERT sflight-carrid

sflight-connid

sflight-fldate

sflight-planetype INTO detail.

ENDFORM. " SET_DETAIL_FIELDS

*&------------------------------------------------------------------*

*& Form EXTRACT_THE_DATA

*&------------------------------------------------------------------*

* text

*-------------------------------------------------------------------*

* --> p1 text

* <-- p2 text

*-------------------------------------------------------------------*

FORM extract_the_data.

*

SELECT carrid connid fldate planetype

FROM sflight

INTO (sflight-carrid, sflight-connid,

sflight-fldate, sflight-planetype).

EXTRACT detail.

ENDSELECT.

*

IF NOT sy-subrc IS INITIAL.

WRITE: / 'No records found in SFLIGHT'(e01).

EXIT.

ENDIF.

ENDFORM. " EXTRACT_THE_DATA

© SAP AG TAW12 17-52

*&------------------------------------------------------------------*

*& Form SORT_THE_DATA

*&------------------------------------------------------------------*

* text

*-------------------------------------------------------------------*

* --> p1 text

* <-- p2 text

*-------------------------------------------------------------------*

FORM sort_the_data.

SORT ASCENDING AS TEXT BY <fs1>

<fs2>

<fs3>

<fs4>.

ENDFORM. " SORT_THE_DATA

*&------------------------------------------------------------------*

*& Form NEW_FS1

*&------------------------------------------------------------------*

* text

*-------------------------------------------------------------------*

* --> p1 text

* <-- p2 text

*-------------------------------------------------------------------*

FORM new_fs1.

FORMAT COLOR COL_HEADING.

WRITE: / sy-vline,

<fs1>,

AT sy-linsz sy-vline.

ULINE.

FORMAT COLOR OFF.

ENDFORM. " NEW_FS1

*&------------------------------------------------------------------*

*& Form WRITE_DETAIL

*&------------------------------------------------------------------*

* text

*-------------------------------------------------------------------*

* --> p1 text

* <-- p2 text

*-------------------------------------------------------------------*

FORM write_detail.

WRITE: /5 sy-vline NO-GAP.

© SAP AG TAW12 17-53

*

PERFORM zebra_striping.

*

WRITE: <fs2> NO-GAP,

sy-vline NO-GAP,

<fs3> NO-GAP,

sy-vline NO-GAP,

<fs4> NO-GAP,

sy-vline NO-GAP.

FORMAT COLOR OFF INTENSIFIED ON.

ENDFORM. " WRITE_DETAIL

*&------------------------------------------------------------------*

*& Form ZEBRA_STRIPING

*&------------------------------------------------------------------*

* text

*-------------------------------------------------------------------*

* --> p1 text

* <-- p2 text

*-------------------------------------------------------------------*

FORM zebra_striping.

*

* Division with remainder

div_mod_2_remainder = zebra_stripe_counter MOD 2.

*

IF div_mod_2_remainder IS INITIAL.

FORMAT COLOR COL_HEADING INTENSIFIED OFF.

ELSE.

FORMAT COLOR COL_NORMAL INTENSIFIED ON.

ENDIF.

*

* Increment each time to get alternating colors.

ADD 1 TO zebra_stripe_counter.

*

ENDFORM. " ZEBRA_STRIPING

*&------------------------------------------------------------------*

*& Form RESET_THE_LINE_SIZE

*&------------------------------------------------------------------*

* text

*-------------------------------------------------------------------*

* --> p1 text

© SAP AG TAW12 17-54

* <-- p2 text

*-------------------------------------------------------------------*

FORM reset_the_line_size.

NEW-PAGE LINE-SIZE line_size.

ENDFORM. " RESET_THE_LINE_SIZE

© SAP AG TAW12 18-1

SAP AG 2002

Contents:

l Saving Lists

l Print

l Background Processing

Saving Lists and Background Processing

© SAP AG TAW12 18-2

SAP AG 2002

At the conclusion of this unit, you will be able to:

l Choose among options to save a list.

l Save a list in an area menu.

l Choose among options for generating a printing list.

l Execute a report in a background work process using a variant.

Saving Lists and Background Processing:Unit Objectives

© SAP AG TAW12 18-3

SAP AG 1999

Saving Lists and Background Processing

Saving ListsSaving Lists

PrintingPrinting

Background ProcessingBackground Processing

© SAP AG TAW12 18-4

SAP AG 2002

Flight data

Folders

Options for Saving Lists

+

System

List Save

List

Save/Send

n There are several ways to save a list that you have generated: � In SAP office � As a local file on your PC � In an area menu � In a User‘s Favorites on the main R/3 menu.

n You can also use menu sequence STL-1 in the System menu to save the list, or use the List menu in the standard list status.

© SAP AG TAW12 18-5

SAP AG 2002

Folders

Flight data

Saving Lists in SAPoffice

Personalfolders

My flight dataFlights from Frankfurt 1

LH Lufthansa400 19.01.2001 New York 380400 26.02.2001 New York 380400 02.03.2001 New York 380402 21.04.2001 New York 189 Save

Send

n You can also create folders in SAP office. You can use these folders to store the lists. When a list is placed in the outbox of the personal folders, it can also be sent to other users.

© SAP AG TAW12 18-6

SAP AG 2002

Unconverted Spreadsheet Rich Text Format

Saving Lists as PC Files

Flights from Frankfurt 1

LH Lufthansa400 01/19/2001 New York 380400 01/26/2001 New York 380400 02/02/2001 New York 380402 01/21/2001 New York 189

HTML format

n You can save a list to a PC as a local file in four different formats: � Unconverted (ASCII) � Spreadsheet format (→ Microsoft Excel) � RTF (Rich Text Format → Microsoft Word) � HTML (Web Browser)

n You can use the program RSSOPCDR to specify the default file that the system proposes when the user chooses to save a file to the local PC.

© SAP AG TAW12 18-7

SAP AG 2002

Display flight data

Change flight data+

Programs

Queries

DEMO: Read ...

DEMO: Variant ...

One-line basic list ...

Programs for flight data model

Flights from Frankfurt 1

LH Lufthansa400 01/19/2001 New York 380400 01/26/2001 New York 380400 02/02/2001 New York 380402 01/21/2001 New York 189

Saved Lists in an Area Menu

Goto

Report PreviewSaved lists

Area menu

n Area menus have been converted to tree navigation in Release 4.6A. Type 1 programs and SAP queries can now be added to the area menus, which may already contain transactions. Any programs that do not have a transaction code are automatically allocated one.

n The report trees have been integrated in the area menus in Release 4.6. The report trees are now maintained using the maintenance tools for area menus. You can maintain area menus in the Workbench menu path STL-1. If you have report trees that you want to convert to area menus, use transaction RTTREE_MIGRATION.

n Saved lists are saved with the program itself. If the program has been integrated in an area menu or in a User’s Favorties on the main R/3 menu, then the saved lists will also appear there. You can also use standard program RSRSSLIS to display saved lists.

n A user can access an area menu whenever that area menu has been allocated to an activity group to which the user belongs. You can use the profile generator to allocate an area menu to an activity group.

© SAP AG TAW12 18-8

SAP AG 1999

Saving Lists and Background Processing

Saving ListsSaving Lists

PrintingPrinting

Background ProcessingBackground Processing

© SAP AG TAW12 18-9

SAP AG 2002

Dialog process

REPORT ...

WRITE: ...

Background WP

Spool process

4 1 2 3

List Printing Options

REPORT ...

WRITE: ...

n There are four options for printing a list: � From the selection screen

­ The list is output to print only when it is generated (adjusted to print format) and does not appear on the screen.

­ The list is generated in a dialog work process � From within the program

­ All the choices available when printing from the selection screen ­ This procedure is suitable for interactive lists: (printing details lists). � After the list has been generated

­ The list has already been generated (visible on the screen) and can be formatted within limits. For example, the number of columns in the list cannot be changed after the list is generated.

­ The list is generated in a dialog work process � In the background

­ The list can be printed after it has been generated (as described in one above) ­ The list is generated in a background work process. This procedure is particularly suitable for

long lists, since it does not block a dialog work process during processing.

© SAP AG TAW12 18-10

SAP AG 2002

NameTitleAuthorization

Output deviceNumber of copies

Immediate outputDelete after outputNew spool requestSpool retention periodArchiving mode

Spool control

Spool request

SAP System cover sheetSelection cover sheetRecipientDepartment

Cover sheets

LinesColumnsFormat

Output format

Spool process

Print Parameters

n To print a list, you must enter print parameters. The print parameters which control list output are divided into the following areas: � Output device and number of copies � Spool request � Spool control � Cover sheets � Output format

n You can enter print parameters on the screen or set them directly in the program. Setting print parameters in the program is covered below (NEW-PAGE PRINT ON).

n You can use the function module SET_PRINT_PARAMETERS to set default values for printing an online list. You can execute print from the selection screen or after generation of the list.

© SAP AG TAW12 18-11

SAP AG 2002

REPORT sapbc405_stld_new_page_prt_on.

NEW-PAGE PRINT ON IMMEDIATELY ' ' KEEP IN SPOOL 'X' RECEIVER sy-uname COVER TEXT 'Flight data'(001).

WRITE: ...

NEW

Program-Controlled Printing

NEW-PAGE PRINT ON [PARAMETERS <pri_set> |<p1> <p2> ... ]

[NO DIALOG].

NEW-PAGE PRINT OFF.

NEWNEW--PAGE PRINT ONPAGE PRINT ON

NEWNEW--PAGE PRINT OFF.PAGE PRINT OFF.

n NEW-PAGE PRINT ON triggers a page break, and all the subsequent output is redirected to the spool.

n The print parameters can either be passed on to the system as a field list with the PARAMETERS attribute or, as shown in the above example, specified individually.

n Individual entry of print parameters is not recommended. Consider the case where the user arrives at the print parameter screen and decides not to print; the only option in this case would be to terminate the entire program.

n If you enter parameter NO DIALOG, the list is placed directly in the spool without giving the user any opportunity to change the print parameters at runtime. If you do not enter NO DIALOG, the user is presented with a print parameters screen containing default values at runtime.

n NEW-PAGE PRINT OFF triggers a page break, ends the spool request (sy-spono is assigned), and all subsequent output is once again output on the screen.

© SAP AG TAW12 18-12

SAP AG 2002

REPORT sapbc405_stld_get_print_param ...

DATA: print_parameter_set LIKE pri_params,valid, list_text LIKE print_parameter_set-prtxt.

...START-OF-SELECTION.

CALL FUNCTION EXPORTING

destination = 'LP01'immediately = ' 'release = 'X'receiver = sy-unamelist_text = list_text

IMPORTINGout_parameters = print_parameter_set valid = valid.

IF valid = 'X'.NEW-PAGE PRINT ON PARAMETERS print_params NO DIALOG.

... . ENDIF....END-OF-SELECTION.

IF valid = 'X'. NEW-PAGE PRINT OFF.ENDIF.

Printing with GET_PRINT_PARAMETERS

CALL FUNCTION 'GET_PRINT_PARAMETERS'CALL FUNCTION 'GET_PRINT_PARAMETERS'

print_parameter_set LIKE pri_params,print_parameter_set LIKE pri_params,valid,valid,

NEWNEW--PAGE PRINT ON PARAMETERS print_parameter_set NO DIALOG.PAGE PRINT ON PARAMETERS print_parameter_set NO DIALOG.

NEWNEW--PAGE PRINT OFF.PAGE PRINT OFF.

n The structure for the PARAMETERS attribute of the NEW-PAGE PRINT ON statement must be filled using function module GET_PRINT_PARAMETERS. The structure contains an internal checksum that is calculated by NEW-PAGE PRINT ON. If the checksum is incorrect, the program terminates. Function module GET_PRINT_PARAMETERS calculates the checksum and returns it with out_parameters.

n Function module GET_PRINT_PARAMETERS provides users with a print parameters screen that can be used to modify the print parameters and then determine a complete new set of print parameters. The set is returned using output parameter out_parameters. In successful cases, output parameter valid contains the value X. If the system cannot create a complete set record of print parameters, the structure transferred with out_parameters is empty and valid contains the value space.

n You can transfer print parameters to the function module GET_PRINT_PARAMETERS. The print parameters appear as default values in the print parameters screen.

n The print parameters screen of function module GET_PRINT_PARAMETERS offers the option of canceling the filling of print parameters. In this case, the structure transferred with out_parameters is empty and valid contains the value space.

© SAP AG TAW12 18-13

SAP AG 2002

GET_PRINT_PARAMETERS: Applications

REPORT sapbc405_stld_diff_receiver ...LOOP ...receiver = ...department = ...

CALL FUNCTION 'GET_PRINT_PARAMETERS'EXPORTING

department = departmentnew_list_id = 'X'no_dialog = 'X'receiver = receiver...

IMPORTINGout_parameters = print_parameters_setvalid = valid

EXCEPTIONS ...

IF valid <> space.NEW-PAGE PRINT ON PARAMETERS print_parameters_set NO DIALOG.PERFORM list_generator.

NEW-PAGE PRINT OFF.WRITE: / 'Spool ID'(001), sy-spono.

....ENDLOOP.

NEWNEW--PAGE PRINT OFF.PAGE PRINT OFF.

NEWNEW--PAGE PRINT ON PARAMETERS PAGE PRINT ON PARAMETERS printprint__parametersparameters__setset NO DIALOG.NO DIALOG.

sysy--sponospono

CALL FUNCTION 'GET_PRINT_PARAMETERS'CALL FUNCTION 'GET_PRINT_PARAMETERS'

n One application is to send a list to several recipients. n Sending a list to several recipients is implemented in the above example. To send a list to several

recipients, you to distribute the list among several spool requests. To do this, use parameter NEW_LIST_ID and then NEW-PAGE PRINT OFF to end the spool request.

© SAP AG TAW12 18-14

SAP AG 1999

Saving Lists and Background Processing

Saving ListsSaving Lists

PrintPrint

Background ProcessingBackground Processing

© SAP AG TAW12 18-15

SAP AG 2002

Define job

Steps

Start date

Job overview

Status

Planned

Released

Ready

Active

Canceled

Print

Save job

The Phases of Background Processing

n When a program converts large datasets and requires a long runtime, it makes sense to execute it in a background work process.

n Background runs take place without user dialogs, and can take place in parallel to online operations. The dialog work processes are available for online processing. Background job runs are performed by special work processes (background processes), which enable distributed processing.

n To start a program in the background, you must first add it to a job. n Use the job definition to determine which programs (steps) will run during this job. You can specify

print parameters and set the start time for the job. n The job overview tells you the current status of the job. n From release 4.6C, a job wizard is available to make the creation of background jobs easier.

© SAP AG TAW12 18-16

SAP AG 2002

General information

Job name MY_JOB

Status Planned

Job class C

SpoolSave

Defining Steps

Destination

Start condition Steps

Name SAPBC405_SSCD_VARIANTS

Language EN

Variant DEMO: BC405

Printing information

ABAP program External command

ABAP program

n Define job is located under menu path STL-2. First assign a job name (of your choice) and define the priority (job class) and the destination (F4 help).

n Determine the individual steps of the job. If you want the program to run with a selection screen, you also have to specify a variant. The list can be stored in the spool or printed immediately. This depends on the specified print parameters. When you have defined all the steps, save them and return to the initial screen of the job definition.

© SAP AG TAW12 18-17

SAP AG 2002

00:00:00

General information

Job name MY_JOB

Status Planned

Job class C

Destination

Start condition Steps

Save Save job

Determining the Start Date and Releasing the Job

Now Date/Time

Date/Time

Planned start 01/01/2001

Do not start after

n Once you have defined the steps, you can determine the start date for the job. For example, you can start the job on a certain day at a certain time.

n Once you have defined the start date, save your entries and return to the initial screen of the job definition. Now save the job, which releases it to run at the specified time.

n You can also use the automated job scheduling with the function modules in function groups BTCH and BTC2. An example is available in program SAPBC405STLD_E_JOB.

© SAP AG TAW12 18-18

SAP AG 2002

Saving Lists and Background Processing: Unit Summary

You are now able to:

l Choose among options to save a list.

l Save a list in an area menu.

l Choose among options for generating a printing list.

l Start a report with a variant in the background.

© SAP AG TAW12 18-19

Savings Lists and Background Processing Exercises

Unit: Saving Lists and Background Processing

Topic: Program-Controlled Printing

When you have completed these exercises, you will be able to:

• Print using function module GET_PRINT_PARAMTERS

1-1 Copy or enhance your program Z##LDB2_..., or copy the sample solution, SAPBC405_LDBS_2, to program Z##STL1_... Sample solution for exercise: SAPBC405_STLS_1.

1-1-1 Enhance the program to include the function for storing the generated list in the spool. To do this, use function module GET_PRINT_PARAMETERS. Use the pattern functions available in the ABAP Editor to program the function call. Pass the following values on in the interface:

EXPORTING: copies = 2, destination = LP01, expiration = 3, immediately = space, line_size = 83, list_text = text-xxx (text element), no_dialog = space, release = X, report = EXAMPLE

IMPORTING: out_parameters = print_parameter, valid = valid

1-1-2 In the TOP include, create variable print_parameter as a character field with length 1, in accordance with DDIC structure PRI_PARAMS and variable valid.

1-1-3 Evaluate the return value of valid after the function call. If valid is not equal to space, store the list in the spool and suppress the print dialog. In addition, display information message 104 from message class BCTRAIN. If valid is equal to space, output information message 105 from message class BC405.

© SAP AG TAW12 18-20

Saving Lists and Background Processing Solutions - Optional

Unit: Saving Lists and Background Processing

Topic: Program-Controlled Printing

*&---------------------------------------------------------------------*

*& Report SAPBC405_STLS_1 *

*& *

*&---------------------------------------------------------------------*

*& *

*& *

*&---------------------------------------------------------------------*

INCLUDE BC405_STLS_1TOP.

*&---------------------------------------------------------------------*

*& Event GET SPFLI

*&---------------------------------------------------------------------*

GET spfli.

* Data output SPFLI

FORMAT COLOR COL_HEADING INTENSIFIED OFF.

WRITE: / sy-vline, spfli-carrid,

spfli-connid,

spfli-cityfrom,

spfli-airpfrom,

spfli-cityto,

spfli-airpto,

AT line_size sy-vline.

*&---------------------------------------------------------------------*

*& Event GET SFLIGHT

*&---------------------------------------------------------------------*

GET sflight.

* Calculate free seats

free_seats = sflight-seatsmax - sflight-seatsocc.

© SAP AG TAW12 18-21

* Data output SFLIGHT

FORMAT COLOR COL_NORMAL INTENSIFIED ON.

WRITE: / sy-vline, sflight-fldate,

sflight-price CURRENCY sflight-currency,

sflight-currency,

sflight-planetype,

sflight-seatsmax,

sflight-seatsocc,

free_seats,

AT line_size sy-vline.

*&---------------------------------------------------------------------*

*& Event GET SBOOK

*&---------------------------------------------------------------------*

GET sbook.

* Check select-option

CHECK so_odat.

FORMAT COLOR COL_NORMAL INTENSIFIED OFF.

WRITE: / sy-vline, sbook-bookid,

sbook-customid,

sbook-smoker,

sbook-luggweight UNIT sbook-wunit,

sbook-wunit,

sbook-order_date,

AT line_size sy-vline.

*&---------------------------------------------------------------------*

*& Event GET SPFLI LATE

*&---------------------------------------------------------------------*

GET spfli LATE.

ULINE.

NEW-PAGE.

*&---------------------------------------------------------------------*

*& Event GET SFLIGHT LATE

*&---------------------------------------------------------------------*

GET sflight LATE.

ULINE.

*&---------------------------------------------------------------------*

© SAP AG TAW12 18-22

*& Event END-OF-SELECTION

*&---------------------------------------------------------------------*

END-OF-SELECTION.

* Define print parameters via function module

CALL FUNCTION 'GET_PRINT_PARAMETERS'

EXPORTING

COPIES = 2 " Number of copies

DESTINATION = 'LP01' " Printer

EXPIRATION = 3 " Duration /d in spool

IMMEDIATELY = SPACE " print immediately

LINE_SIZE = 100 " Width of list

LIST_TEXT = TEXT-SP1 " Title

NO_DIALOG = SPACE " dialog is allowed

RELEASE = 'X' " delete task after print

REPORT = 'EXAMPLE' " Name

IMPORTING

OUT_PARAMETERS = PRINT_PARAMETER

VALID = VALID.

* Sending list to the SAP spool or on the screen

IF VALID NE SPACE. " List to spool

NEW-PAGE PRINT ON PARAMETERS PRINT_PARAMETER NO DIALOG.

MESSAGE I104(BC405).

ELSE. " List on screen

MESSAGE I105(BC405).

ENDIF.

*&---------------------------------------------------------------------*

*& Include BC405_STLS_1TOP *

*& *

*&---------------------------------------------------------------------*

REPORT sapbc405_stls_1 LINE-SIZE 83.

* Used nodes of the structure of the logical database F1S

NODES: spfli, sflight, sbook.

* Additional selections

SELECTION-SCREEN BEGIN OF BLOCK order WITH FRAME.

SELECT-OPTIONS: so_odat FOR sbook-order_date.

SELECTION-SCREEN END OF BLOCK order.

© SAP AG TAW12 18-23

* Variables

DATA: free_seats LIKE sflight-seatsocc.

DATA: print_parameter LIKE pri_params, " NEW-PAGE PRINT ON .....

valid VALUE 'X'.

* Constants

CONSTANTS: line_size LIKE sy-linsz VALUE 83,

pos_lev2 TYPE i VALUE 10,

pos_lev3 TYPE i VALUE 20.

© SAP AG TAW12 19-1

SAP AG 2002

Basic Techniques in Interactive Lists

Contents:

l Detail lists

l Interactive events

l Data transport between list and program

n Hide technique

n Valid line selection

n Querying cursor position

l Page headings for detail lists

l List in modal dialog boxes

© SAP AG TAW12 19-2

SAP AG 2002

At the conclusion of this unit, you will be able to:

Basic Techniques in Interactive Lists: Objectives

l Describe what detail lists are and how to generate them.

l Identify which interactive events exist.

l Transport data between lists and programs.

l Recognize an invaild line selection.

l Create page headers in detail lists.

l Create lists in modal dialog boxes.

© SAP AG TAW12 19-3

SAP AG 2002

Basic Techniques in Interactive Lists

Detail listsDetail lists

Data transportData transport

Other techniquesOther techniques

© SAP AG TAW12 19-4

SAP AG 2002

Basic list

DL 1DL 2

DL 20

Navigating Between Lists

double-click on line

n Up to 20 parallel detail lists can exist for each basic list. Each list has in its own individual memory area called a list buffer.

n The same functions are available in detail lists as are available in basic lists. n Choose Back (the green arrow) or Cancel (the red X) to leave the current list. This releases the

corresponding list buffer and returns to the preceding list. n Use the Exit function (yellow arrow) to return to the selection screen.

© SAP AG TAW12 19-5

SAP AG 2002

* Basic list

START-OF-SELECTION.

GET ... .

END-OF-SELECTION.

TOP-OF-PAGE.

* Detail lists

AT LINE-SELECTION.

AT USER-COMMAND.

TOP-OF-PAGE DURING LINE-SELECTION.

Events: Overview

n The events START-OF-SELECTION, GET, END-OF-SELECTION, TOP-OF-PAGE and END-OF-PAGE can be used only to create basic lists. Once you leave a basic list, these events are no longer processed.

n Detail lists are created using two basic events: AT LINE-SELECTION and AT USER-COMMAND. The event TOP-OF-PAGE DURING LINE-SELECTION is used to create headers for all detail lists. If the application displays multiple detail lists, use the CASE keyword with system field sy-dynnr detemine which secondary headings to display.

© SAP AG TAW12 19-6

SAP AG 2002

Program Flow in Detail Lists

DEMO: List ...

SY-UCOMMF2

PICK

SY-UCOMM

%EX

PRI

P+

P-

. . .

REPORT SAPBC405_...

AT LINE-SELECTION.AT LINEAT LINE--SELECTION.SELECTION.

System programs

List Edit Goto System Help

n If the report has a custom GUI and the user selects a menu option, the event AT USER-COMMAND is triggered. The function code assigned to the menu option can be evaluated using a CASE construct to determine which menu option was selected.

n If the user double-clicks on a report line, the AT LINE-SELECTION event is triggered. The event can also be triggered by single clicking on a report line and either pressing the Detail icon in the application tool bar, pressing F2, or entering the word PICK in the OK code field and pressing Enter.

© SAP AG TAW12 19-7

SAP AG 2002

REPORT sapbc405_ilbd_interact_list_1.

...

AT LINE-SELECTION.

WRITE:‚This is a detail list'(001)COLOR COL_TOTAL, / 'List level: '(002), sy-lsind, ...

Creating Detail Lists I

Basic list

User action sy-ucomm = PICK

AT LINEAT LINE--SELECTION.SELECTION.

This is a detail listList level: 1

n When the PICK function is triggered, the program is given control, and the interactive event AT LINE-SELECTION is processed. All the subsequent output (WRITE, ULINE, or SKIP) is output in a details list.

n The system field SY-LSIND indicates the current list level and is increased by one whenever event AT LINE-SELECTION or the AT USER-COMMAND event is processed.

© SAP AG TAW12 19-8

SAP AG 2002

REPORT sapbc405_ilbd_interact_lists_2.

AT LINE-SELECTION.

CASE sy-lsind.

WHEN '1'.WRITE: 'Detail list: 1'(001),

/'SY-LSIND: '(000), sy-lsind.

WHEN '2'.WRITE: 'Detail list: 2'(002),

/'SY-LSIND: '(000), sy-lsind.

ENDCASE.

Detail list: 1sy-lsind: 1

Detail list: 2sy-lsind: 2

PICK

PICK

Basic listsy-lsind: 0

PICK

Creating Detail Lists II

AT LINEAT LINE--SELECTION.SELECTION.

sysy--lsindlsind..

WHEN 1.WHEN 1.

WHEN 2.WHEN 2.

n The system field SY-LSIND is incremented by one each time the AT USER-COMMAND or AT LINE-SELECTION events are triggered. You can determine the number of the new list buffer by using a CASE construct with the system field SY-LSIND.

n You control the maximum number of detail lists that will be displayed. In the above example, no third list is generated. If the AT LINE-SELECTION event is triggered while viewing list 2, the value of sy-lsind increments to three but since no WRITE, ULINE, or SKIP is executed, the system sets SY-LISIND back to two and detail list two remains visible.

© SAP AG TAW12 19-9

SAP AG 2002

Basic Techniques in Interactive Lists

Detail listsDetail lists

Data transportData transport

Other techniquesOther techniques

© SAP AG TAW12 19-10

SAP AG 2002

HIDE: <f1>, <f2>, ... .

DEMO: Data Transport: Hide Technique--------------------------------------------------------AA NEW YORK SAN FRANCISCOAZ ROME FRANKFURTAZ TOKYO ROME LH FRANKFURT NEW YORK

REPORT sapbc405_ilbd_hide .

GET spfli FIELDS carrid connid cityfrom cityto.

WRITE: / spfli-carrid,10 spfli-cityfrom,

(24) spfli-cityto.

HIDE: spfli-carrid,spfli-connid.

AT LINE-SELECTION....

HIDE Area

WRITE:WRITE:

HIDE:HIDE:

33:66:

spfli-carridspfli-connid

: spfli-carridspfli-connid

:

AA0017

:LH0400

:

HIDE area of list level 0

Line Field name Value

n If you want to show supporting data for a selected line, you will need to know which line was selected. The HIDE keyword is used to store data objects and their values so they can be made available when the User selects a report line. When a line is selected, the fields that were hidden are filled with the values that you hid for that line. You can hide fields you do not write and write fields you do not hide.

n You typically use the HIDE statement to save the key fields or other information that you are required to read additional information.

n The HIDE keyword must be coded immediately after the last write sentence on the output line. The system field SY-LILLI is incremented each time a line feed character is encountered or any time an output line wraps to a second line if the line size is too small. Care must be taken to ensure that the detail line does not wrap, since the data objects you hide will not match the line selected by the user.

© SAP AG TAW12 19-11

SAP AG 2002

DEMO: Data Transport: Hide Technique--------------------------------------------------------AA NEW YORK SAN FRANCIAZ ROME FRANKFURTAZ TOKYO ROME LH FRANKFURT NEW YORK

SY-LILLI

REPORT SAPBC405_ILBD_HIDE .

AT LINE-SELECTION.

SELECT ...WHERE carrid = spfli-carrid

AND connid = spfli-connid.

1

4

3

2 5

Line Selection: The Hide Technique

DEMO: Data Transport: Hide Technique--------------------------------------------------------LH 400

02.01.2002 1,332.00 DEM03.28.2002 1,332.00 DEM04.17.2002 1,332.00 DEM

AT LINEAT LINE--SELECTION.SELECTION.

0400

LH

33:66:

spfli-carridspfli-connid

: spfli-carridspfli-connid

:

AA0017

:LH0400

:

HIDE area of list level 0

Line Field name Value

6

n The individual steps of the above example are described below: � The user selects a line for which data has been stored in the HIDE area. This can be done either by

double clicking on a line or, if the field or line was written with HOTSPOT ON, a single click will react like a double click.The runtime system evaluates field SY-LILLI to determine the selected line: in this case line six. � The runtime system jumps to the point in the HIDE area where data for this line is stored. � The runtime system then inserts all values stored for the selected line in the HIDE area into their

corresponding fields. � The runtime system processes the event AT LINE-SELECTION and its corresponding program

processing block. � A detail list is created.

© SAP AG TAW12 19-12

SAP AG 2002

Basic list DL 1 DL 2

HIDE areaBasic list

. . .

HIDE areaDetail List

List bufferBasic list

List bufferDetail List

List bufferDetail List

HIDE areaDetail List

Detail List Buffering

Display Display Display

n All the output for a list is saved in a list buffer. As a result, each list remains saved in the system until the list buffer is deleted. All the details lists whose list level is greater than the current list level are deleted automatically by the runtime system (that is, their list buffer is deleted). For example, when you branch from details list five to detail list three, the list buffers of detail lists four and five are deleted.

n Each list level is allocated its own HIDE area.

© SAP AG TAW12 19-13

SAP AG 2002

REPORT sapbc405_ilbd_valid_line_sel....

GET spfli FIELDS ...WRITE ...HIDE: spfli-carrid, spfli-connid.

END-OF-SELECTION.CLEAR spfli-carrid.

AT LINE-SELECTION.CHECK NOT spfli-carrid IS INITIAL....

CLEAR spfli-carrid.

HIDE area

Valid line selection

CLEARCLEAR spflispfli--carridcarrid..

CHECK NOTCHECK NOT spflispfli--carridcarrid IS INITIAL.IS INITIAL.

CLEARCLEAR spflispfli--carridcarrid..

DEMO: Data Transport: Hide Technique--------------------------------------------------------LH 400

01.02.02 1.332,00 DEM28.03.02 1.332,00 DEM17.04.02 1.332,00 DEM

n You must ensure that when you choose a line for which no data has been stored in the HIDE area, this is interpreted as an invalid line selection. Invalid lines include headers and footers.

n When necessary, you can ensure that no detail lists are created for invalid line selections. n The field spfli-carrid, whose contents have been stored in the HIDE area, is initialized in the

programming example above. If a user chooses an invalid line, the runtime system will not find a value in the HIDE area. The field retains its initial value. The CHECK statement then reads this initial value and the program exits the current processing block (AT LINE-SELECTION). No detail list is generated and the current list buffer remains in view.

© SAP AG TAW12 19-14

SAP AG 2002

Basic Techniques in Interactive Lists

Detail listsDetail lists

Data transportData transport

Other techniquesOther techniques

© SAP AG TAW12 19-15

SAP AG 2002

Setting GUI Titles

Title Flight data for airline &1

SET TITLEBAR 'T01'

[WITH <f1> <f2> ..<f9>]

Maintain title

Create Title

Double-click

Program

Title code

SAPBC405_ILBD_GUI_TITLE

T01

OK All titles

SY-TITLESY-TITLE

n Title names can be up to 20 characters in length and must be entered all in capital letters. A title that is set stays active until a new one is set.

n You can display up to 9 variables within the GUI title using SET TITLEBAR <TITLE> WITH <f1>. The total length of title including all variables cannot exceed 70 characters in length.

© SAP AG TAW12 19-16

SAP AG 2002

TOP-OF-PAGE DURING LINE-SELECTION.

REPORT sapbc405_ilbd_heading_i_lists NO STANDARD PAGE HEADING.

TOP-OF-PAGE.

TOP-OF-PAGE DURING LINE-SELECTION.

Basic list

Detail list

Page Headings for Detail Lists

TOPTOP--OFOF--PAGE DURING LINEPAGE DURING LINE--SELECTIONSELECTION..

n The TOP-OF-PAGE event is only processed when you create a basic list. n The TOP-OF-PAGE DURING LINE-SELECTION event is used to create headers for each of the

detail lists. Evaluate the system field SY-LSIND to determine which headings to display. n TOP-OF-PAGE DURING LINE-SELECTION is triggered by the first output (such as WRITE) in

each new list page. n When the user selects a line, the system field SY-LISEL is populated with the image of the selected

line. This can be used as a heading for the detail list buffer to show which list line was selected. Sample coding might be:

TOP-OF-PAGE DURING LINE-SELECTION. FORMAT COLOR COL_HEADING ULINE WRITE: / sy-lisel. ULINE.

© SAP AG TAW12 19-17

SAP AG 2002

DEMO: Modal Dialog Box

WINDOW STARTING AT <c1> <r1>[ENDING AT <c2> <r2>].

REPORT sapbc405_ilbd_g_window.

DATA: ... line1 TYPE i, line2 TYPE i....

AT LINE-SELECTION....

line1 = sy-curow + 1. line2 = line1 + 12.

WINDOW STARTING AT 10 line1ENDING AT 65 line2.

´ WRITE ......

Creating Lists in Modal Dialog Boxes

DEMO: Modal Dialog Box-------------------------------------------------------------AA NEW YORK SAN FRANCISCOAZ ROME FRANKFURTAZ TOKYO ROM LH FRANKFURT NEW YORK LHLHQFQFSQ SINGAPORE SAN FRANCISCO

AT LINEAT LINE--SELECTION.SELECTION.

WINDOW STARTING AT 10 line1 WINDOW STARTING AT 10 line1 ENDING AT 65 line2.ENDING AT 65 line2.

AZ 055519.05.2002 360.202 ITL21.08.2002 360.202 ITL

<c1> <r1> <c2> <r2>

Demo: Modal Dialog Box

n You can display the current detail list in a modal dialog box with statement WINDOW STARTING AT.

n The upper-left corner of a modal dialog box is positioned at column <c1> row <r1>. The count begins at zero/zero in the upper-left corner of the main window. If <r1> is less than or equal to zero, the list displays in full screen format instead of a modal dialog box.

n You can use the optional parameter ENDING to set the length and width of a modal dialog box: The lower-right corner is positioned at column <c2> row <r2>.

n You can create a title for the modal dialog box with SET TITLEBAR '<title>’, as well as a modal dialog box GUI. A custom GUI is not really necessary since the system automatically supplies a standard GUI for all modal dialog boxes.

© SAP AG TAW12 19-18

SAP AG 2002

GET CURSOR FIELD <feld1> [VALUE <feld2>].

REPORT sapbc405_ilbd_field_selection.

DATA: ... ,field_name(30), field_value(50).

...AT LINE-SELECTION.GET CURSOR FIELD field_name

VALUE field_value.

CASE field_name.WHEN 'SPFLI-CARRID'....

WHEN 'SPFLI-CONNID'....

ENDCASE.

Field Selection

DEMO: Field Selection--------------------------------------------------------CARRID CONNID CITYFROMAA 0017 NEW YORKAZ 0555 ROMEAZ 0789 TOKYO LH 0400 FRANKFURT

DEMO: Field Selection

LH: Lufthansa

DEMO: Field Selection

LH 040019.05.200221.08.2002

field_name(30), field_value(50).field_name(30), field_value(50).

GET CURSOR FIELD field_name GET CURSOR FIELD field_name VALUE field_value.VALUE field_value.

field_name.field_name.'SPFLI'SPFLI--CARRID'.CARRID'.

'SPFLI'SPFLI--CONNID'.CONNID'.

n You can use the GET CURSOR statement to create detail lists according to the cursor position. If a user clicks on one of the CARRID fields in the example above, the name of the corresponding airline is displayed. If a user clicks on one of the CONNID fields, all flight dates for that particular flight number are displayed instead.

n The parameter FIELD provides the name of an output field. The parameter VALUE provides the output value.

n The return value SY-SUBRC is set to: l Value 0: The cursor is positioned on a field l Value 4: The cursor is not positioned on a field

n Note: Do not use the value of parameter VALUE in the WHERE condition of a SELECT statement, because this can lead to type conversions for non-character fields that produce undesirable results. It is better to use the HIDE technique in this case.

© SAP AG TAW12 19-19

SAP AG 2002

System Fields for Interactive Lists

SY-CUROWSY-CUROW

2 SY-CPAGESY-CPAGE

1 SY-PAGNOSY-PAGNO

SY-CUCOLSY-CUCOL3

SY-LILLISY-LILLI

1234

1234

5678

5678

9109

10

1234

1234

SY-LINNOSY-LINNO

Basic list

. . .SY-LSIND = 0SY-LSIND = 0

SY-LISTI = 0SY-LISTI = 0

DL 2DL 1

SY-LSIND = 1SY-LSIND = 1

SY-LISTI = 0SY-LISTI = 0SY-LSIND = 2SY-LSIND = 2

SY-LISTI = 1SY-LISTI = 1

n The following system fields are automatically supplied with values at each interactive event: SY-LSIND Index for the current list SY-LISTI Index of the last list displayed SY-LILLI Absolute number of a selected line in the list displayed SY-CPAGE Number of the upper-most displayed line in the list displayed SY-CUCOL Number of the column in the window where the cursor was last positioned in the list displayed SY-CUROW Number of the line in the window where the cursor was last positioned in the list displayed SY-STACO Number of the first column displayed in the list displayed SY-STARO Number of the first visible line in the top displayed page (SY-PAGE) in the list displayed (not including header lines) SY-UCOMM Function code that triggered the interactive event in the list displayed SY-PFKEY Status of the list displayed

© SAP AG TAW12 19-20

SAP AG 2002

Basic Techniques in Interactive Lists: Summary

You are now able to:

l Describe what detail lists are and generate them.

l Identify which interactive events exist.

l Transport data between lists and programs.

l Recognize an invalid line selection.

l Create page headers in detail lists.

l Create lists in modal dialog boxes.

© SAP AG TAW12 19-21

Interactive Lists Exercises

Unit: Interactive Lists

Topic: Printing Detail Lists

When you have completed these exercises, you will be able to:

• Use interactive event AT LINE-SELECTION.

• Use the hide technique.

• Use valid line selection.

• Set GUI titles.

1-1 Copy or enhance your program Z##DAP1_..., or copy the sample solution, SAPBC405_DAPS_1, to program Z##ILB1_... . Sample solution for exercise: SAPBC405_ILBS_1.

The user needs to be able to display bookings for a flight in a detail list.

1-1-1 Enable the user to display the bookings for a flight in a detail list by selecting (Format HOTSPOT) a line with the flight dates. The detail list should contain the following fields:

bookid (table sbook) customid (table sbook) form (table scustom) name (table scustom) order_date (table sbook) class (table sbook)

1-1-2 To do this, create an appropriate internal table in the TOP include (type: standard) and a working area.

1-1-3 Make sure that only flights for which seats are already occupied are output in HOTSPOT format (sflight-seatsocc > 0).

1-1-4 Output the booking number and the customer number in color COL_KEY, and the other fields in color COL_NORMAL.

1-1-5 No other details option should be possible within the booking list.

1-2 Prevent invalid line selections.

© SAP AG TAW12 19-22

1-3 Collect the required data for the detail list at event AT LINE-SELECTION.

1-3-1 Encapsulate the data collection and the data output in one subroutine each. Read the data from table SBOOK and the corresponding data from table SCUSTOM. The key relationshi[p between SBOOK and SCUSTOM is SBOOK-BOOKID=SCUSTOM-CUSTOMID.

There are two ways of reading the data:

• You can read the data from table SBOOK in a SELECT loop and then read the appropriate data record from SCUSTOM (SELECT SINGLE).

• You can program an INNER JOIN for both tables.

1-3-2 If the user selects a flight for which no seats have yet been booked, then display information message 004 from message class BC405.

1-4 Set a GUI title for the basic list and the detail list.

1-4-1 The title of the basic list should contain the dates specified in the selection screen (flight connections from … to …).

© SAP AG TAW12 19-23

Exercises

Unit: Interactive Lists

Topic: Printing Detail Lists

When you have completed these exercises, you will be able to:

• Utilize the cursor position.

• Display lists in a modal dialog window.

• Set headers in detail lists.

2-1 Copy or enhance your program Z##ILB1_..., or copy the sample solution, SAPBC405_ILBS_1, to program Z##ILB2_... Sample solution for exercise: SAPBC405_ILBS_2.

Give the user an option to display additional information for airlines in a modal dialog window.

2-1-1 Allow the user to display additional information for the airline by selecting the airline code. To do this, output the name, short description, and the local currency of the airline in a modal dialog window.

Position the modal dialog box in such a way that it is opened in the line that the user has selected, but three columns further right. Use the system variables SY-CUCOL and SY-CUROW.

2-1-2 To control the output of the detail list for event AT LINE-SELECTION, use the name of the field where the cursor was positioned when the event was triggered (GET CURSOR ... ).

2-1-3 Encapsulate the collection of the appropriate data (table SCARR) and its output in a subroutine.

2-1-4 Display a page header in both the dialog window and in the booking list. The booking list should contain the short name of the airline, the flight number, and the flight date. Display column headers in the booking list.

2-1-5 Ensure that the modal dialog box has a GUI title.

© SAP AG TAW12 19-24

Interactive Lists Solutions

Unit: Interactive Lists

Topic: Printing Detail Lists

*&---------------------------------------------------------------------*

*& Report SAPBC405_ILBS_1 *

*& *

*&---------------------------------------------------------------------*

*& Solution; Exercise 1; Basic Techniques ... *

*& *

*&---------------------------------------------------------------------*

INCLUDE bc405_ilbs_1top.

*&---------------------------------------------------------------------*

*& Event TOP-OF-PAGE

*&---------------------------------------------------------------------*

TOP-OF-PAGE.

* Title

FORMAT COLOR COL_HEADING INTENSIFIED ON.

ULINE.

WRITE: / sy-vline,

'Flight data'(001),

AT line_size sy-vline.

ULINE.

* Column header

FORMAT COLOR COL_HEADING INTENSIFIED OFF.

WRITE: sy-vline, 'Departure location'(004), AT line_size sy-vline.

WRITE: sy-vline, 'Arrival location'(004), AT line_size sy-vline.

WRITE: sy-vline, AT pos_c1 'Flight'(002).

* Fix left scroll boundary

SET LEFT SCROLL-BOUNDARY.

WRITE: 'Date'(003),

© SAP AG TAW12 19-25

AT pos_c3 'Price'(006),

AT pos_c4 'Max.'(008),

AT pos_c5 'Occ.'(009),

AT line_size sy-vline.

ULINE.

*&---------------------------------------------------------------------*

*& Event INITIALIZATION

*&---------------------------------------------------------------------*

INITIALIZATION. " OPTIONAL

* Initialize select-options for CARRID

MOVE: 'AA' TO so_car-low,

'QF' TO so_car-high,

'BT' TO so_car-option,

'I' TO so_car-sign.

APPEND so_car.

CLEAR so_car.

MOVE: 'AZ' TO so_car-low,

'EQ' TO so_car-option,

'E' TO so_car-sign.

APPEND so_car.

CLEAR so_car.

*&---------------------------------------------------------------------*

*& Event AT SELECTION-SCREEN ON BLOCK PARAM

*&---------------------------------------------------------------------*

AT SELECTION-SCREEN ON BLOCK param. " OPTIONAL

* check country for national flights is not empty

CHECK national = 'X' AND country = space.

MESSAGE e003(bc405).

*&---------------------------------------------------------------------*

*& Event START-OF-SELECTION

*&---------------------------------------------------------------------*

START-OF-SELECTION.

* Checking the output parameters

CASE mark.

WHEN all.

© SAP AG TAW12 19-26

* Radiobutton ALL is marked

SELECT * FROM spfli INNER JOIN sflight

ON spfli~carrid = sflight~carrid

AND spfli~connid = sflight~connid

INTO CORRESPONDING FIELDS OF TABLE it_flights

WHERE spfli~carrid IN so_car

AND spfli~connid IN so_con

AND sflight~fldate IN so_fdt.

WHEN national.

* Radiobutton NATIONAL is marked

SELECT * FROM spfli INNER JOIN sflight

ON spfli~carrid = sflight~carrid

AND spfli~connid = sflight~connid

INTO CORRESPONDING FIELDS OF TABLE it_flights

WHERE spfli~carrid IN so_car

AND spfli~connid IN so_con

AND sflight~fldate IN so_fdt

AND spfli~countryfr = spfli~countryto

AND spfli~countryfr = country.

WHEN internat.

* Radiobutton INTERNAT is marked

SELECT * FROM spfli INNER JOIN sflight

ON spfli~carrid = sflight~carrid

AND spfli~connid = sflight~connid

INTO CORRESPONDING FIELDS OF TABLE it_flights

WHERE spfli~carrid IN so_car

AND spfli~connid IN so_con

AND sflight~fldate IN so_fdt

AND spfli~countryfr NE spfli~countryto.

ENDCASE.

*&---------------------------------------------------------------------*

*& Event END-OF-SELECTION

*&---------------------------------------------------------------------*

END-OF-SELECTION.

*SORT it_flights BY carrid connid fldate.

© SAP AG TAW12 19-27

* Control Level Processing: the internal table has to be sorted

SORT it_flights BY cityfrom cityto carrid connid.

* Data output

PERFORM data_output.

* clear hidden field for valid line selection

CLEAR: wa_flights-fldate.

* Set GUI title for base list

SET TITLEBAR 'T_BASE' WITH so_fdt-low so_fdt-high.

*&---------------------------------------------------------------------*

*& Event AT LINE-SELECTION

*&---------------------------------------------------------------------*

AT LINE-SELECTION.

* no higher display lists allowed

CHECK sy-lsind < 2.

* only valid line selections

CHECK NOT wa_flights-fldate IS INITIAL.

IF wa_flights-seatsocc < 1.

* info message for flights without bookings

MESSAGE i004(bc405).

ELSE.

* get booking data

PERFORM booking_select.

* output for flights with bookings

PERFORM booking_output.

* clear hidden field for valid line selection

CLEAR wa_flights-fldate.

ENDIF.

* Set GUI title for secondary list

SET TITLEBAR 'T_LIST1'.

*&---------------------------------------------------------------------*

*& Form DATA_OUTPUT

© SAP AG TAW12 19-28

*&---------------------------------------------------------------------*

* List output of flight data

*----------------------------------------------------------------------*

FORM data_output.

* Loop at the internal table for writing data

LOOP AT it_flights INTO wa_flights.

* Group Level: CITYFROM

AT NEW cityfrom.

NEW-PAGE.

FORMAT COLOR COL_GROUP INTENSIFIED ON.

WRITE: / sy-vline, wa_flights-cityfrom,

AT line_size sy-vline.

FORMAT RESET.

ENDAT.

* Group Level: CITYTO

AT NEW cityto.

FORMAT COLOR COL_GROUP INTENSIFIED OFF.

WRITE: / sy-vline, wa_flights-cityto,

AT line_size sy-vline.

FORMAT RESET.

ENDAT.

* Single Record Processing

* Hotspot off, if no bookings exist

IF wa_flights-seatsocc < 1.

FORMAT HOTSPOT OFF.

ELSE.

FORMAT HOTSPOT ON.

ENDIF.

* Mark international flights

FORMAT COLOR COL_KEY INTENSIFIED ON.

IF wa_flights-countryfr EQ wa_flights-countryto.

WRITE: / sy-vline, icon_space AS ICON CENTERED.

ELSE.

WRITE: / sy-vline, icon_bw_gis AS ICON CENTERED.

ENDIF.

* Data output

© SAP AG TAW12 19-29

WRITE: wa_flights-carrid,

wa_flights-connid.

FORMAT COLOR COL_NORMAL INTENSIFIED OFF.

WRITE: wa_flights-fldate,

wa_flights-price CURRENCY wa_flights-currency,

wa_flights-currency,

wa_flights-seatsmax,

wa_flights-seatsocc,

AT line_size sy-vline.

* Hide Fields

HIDE: wa_flights-carrid, wa_flights-connid, wa_flights-fldate,

wa_flights-seatsocc.

FORMAT RESET.

* Group Level: CONNID

AT END OF connid.

SUM.

FORMAT COLOR COL_TOTAL.

WRITE: / sy-vline,

'Total'(007),

wa_flights-seatsmax UNDER wa_flights-seatsmax,

wa_flights-seatsocc UNDER wa_flights-seatsocc,

AT line_size sy-vline.

FORMAT RESET.

ENDAT.

* Group Level: CITYFROM

AT END OF cityfrom.

ULINE.

ENDAT.

ENDLOOP.

ENDFORM. " DATA_OUTPUT

*&---------------------------------------------------------------------*

*& Form BOOKING_OUTPUT

*&---------------------------------------------------------------------*

* output of bookings

© SAP AG TAW12 19-30

*----------------------------------------------------------------------*

FORM booking_output.

FORMAT COLOR COL_NORMAL.

LOOP AT it_book INTO wa_book.

WRITE: / wa_book-bookid COLOR COL_KEY,

wa_book-customid COLOR COL_KEY,

wa_book-form,

wa_book-name,

wa_book-order_date,

wa_book-class,

AT sy-linsz space.

ENDLOOP.

ENDFORM. " BOOKING_OUTPUT

*&---------------------------------------------------------------------*

*& Form BOOKING_SELECT

*&---------------------------------------------------------------------*

* selection of booking data

*----------------------------------------------------------------------*

FORM booking_select.

REFRESH it_book.

* Selection via SELECT SINGLE

* SELECT bookid customid class order_date FROM sbook

* INTO CORRESPONDING FIELDS OF wa_book

* WHERE carrid = wa_flights-carrid

* AND connid = wa_flights-connid

* AND fldate = wa_flights-fldate.

* SELECT SINGLE name form telephone FROM scustom

* INTO CORRESPONDING FIELDS OF wa_book

* WHERE id = wa_book-customid.

* APPEND wa_book TO it_book.

* ENDSELECT.

* Selection via INNER JOIN

SELECT bookid customid class order_date

FROM sbook INNER JOIN scustom

ON sbook~customid = scustom~id

INTO CORRESPONDING FIELDS OF TABLE it_book

© SAP AG TAW12 19-31

WHERE carrid = wa_flights-carrid

AND connid = wa_flights-connid

AND fldate = wa_flights-fldate.

ENDFORM. " BOOKING_SELECT

*&---------------------------------------------------------------------*

*& Include BC405_ILBS_1TOP *

*& *

*&---------------------------------------------------------------------*

REPORT sapbc405_ilbs_1 LINE-SIZE 100 NO STANDARD PAGE HEADING.

* Include for using icons

INCLUDE <icon>.

* Linetype of internal table

TYPES: BEGIN OF linetype,

cityfrom LIKE spfli-cityfrom,

cityto LIKE spfli-cityto,

carrid LIKE spfli-carrid,

connid LIKE spfli-connid,

countryfr LIKE spfli-countryfr,

countryto LIKE spfli-countryto,

fldate LIKE sflight-fldate,

price LIKE sflight-price,

currency LIKE sflight-currency,

seatsmax LIKE sflight-seatsmax,

seatsocc LIKE sflight-seatsocc,

END OF linetype.

* Constants for writing position

CONSTANTS: pos_c1 TYPE i VALUE 6,

pos_c3 TYPE i VALUE 30,

pos_c4 TYPE i VALUE 58,

pos_c5 TYPE i VALUE 68,

line_size TYPE i VALUE 100.

* Constant for CASE statement

CONSTANTS mark VALUE 'X'.

© SAP AG TAW12 19-32

* Internal table like DDIC view DV_FLIGHTS

* DATA: it_flights LIKE TABLE OF dv_flights,

* wa_flights LIKE dv_flights.

* Internal table type linetype

DATA: it_flights TYPE STANDARD TABLE OF linetype,

wa_flights TYPE linetype.

* Work area and itab for bookings

DATA: BEGIN OF wa_book,

bookid LIKE sbook-bookid,

customid LIKE sbook-customid,

class LIKE sbook-class,

order_date LIKE sbook-order_date,

name LIKE scustom-name,

form LIKE scustom-form,

END OF wa_book,

it_book LIKE TABLE OF wa_book.

* Selections for connections

SELECTION-SCREEN BEGIN OF BLOCK conn WITH FRAME TITLE text-tl1.

SELECT-OPTIONS: so_car FOR wa_flights-carrid,

so_con FOR wa_flights-connid.

SELECTION-SCREEN END OF BLOCK conn.

* Selections for flights

SELECTION-SCREEN BEGIN OF BLOCK flight WITH FRAME TITLE text-tl2.

SELECT-OPTIONS so_fdt FOR wa_flights-fldate NO-EXTENSION.

SELECTION-SCREEN END OF BLOCK flight.

* Output parameter

SELECTION-SCREEN BEGIN OF BLOCK param

WITH FRAME TITLE text-tl3.

SELECTION-SCREEN BEGIN OF BLOCK radio WITH FRAME.

PARAMETERS: all RADIOBUTTON GROUP rbg1,

national RADIOBUTTON GROUP rbg1,

internat RADIOBUTTON GROUP rbg1 DEFAULT 'X'.

SELECTION-SCREEN END OF BLOCK radio.

PARAMETERS country LIKE wa_flights-countryfr.

SELECTION-SCREEN END OF BLOCK param.

© SAP AG TAW12 19-33

Solutions

Unit: Interactive Lists

Topic: Printing Detail Lists

*&---------------------------------------------------------------------*

*& Report SAPBC405_ILBS_2 *

*& *

*&---------------------------------------------------------------------*

*& Solution; Exercise 2; Basic Techniques ... *

*& *

*&---------------------------------------------------------------------*

INCLUDE bc405_ilbs_2top.

<<<<<<<< *************** >>>>>>>

Not all events shown here. See above for missing events

<<<<<<<< *************** >>>>>>>

*&---------------------------------------------------------------------*

*& Event AT LINE-SELECTION

*&---------------------------------------------------------------------*

AT LINE-SELECTION.

* no higher display lists allowed

CHECK sy-lsind < 2.

* get cursor position

GET CURSOR FIELD field_name.

CASE field_name.

WHEN 'WA_FLIGHTS-CARRID'.

* Set GUI-title for the dialog box

SET TITLEBAR 'T_LIST_MODAL'.

* output of carrier details

PERFORM carrier_output.

© SAP AG TAW12 19-34

WHEN OTHERS.

* only valid line selections

CHECK NOT wa_flights-fldate IS INITIAL.

IF wa_flights-seatsocc < 1.

* info message for flights without bookings

MESSAGE i004(bc405).

ELSE.

* get booking data

PERFORM booking_select.

* output for flights with bookings

PERFORM booking_output.

ENDIF.

* Set GUI title for secondary list

SET TITLEBAR 'T_LIST1'.

ENDCASE.

* clear hidden fields for valid line selection

CLEAR: wa_flights-fldate, wa_flights-carrid.

*&---------------------------------------------------------------------*

*& Event TOP-OF-PAGE DURING LINE-SELECTION

*&---------------------------------------------------------------------*

TOP-OF-PAGE DURING LINE-SELECTION. CASE field_name.

WHEN 'WA_FLIGHTS-CARRID'.

FORMAT COLOR COL_HEADING.

WRITE: / 'Detail display'(d10).

ULINE.

WHEN OTHERS.

* format for page headings on the detail list

FORMAT COLOR COL_HEADING.

* title of the detail list

WRITE: / 'Bookings for'(d00),

wa_flights-carrid NO-GAP,

wa_flights-connid,

© SAP AG TAW12 19-35

wa_flights-fldate,

AT sy-linsz space.

ULINE.

* headings of the detail list

WRITE: / 'Booking'(d01),

'Customer no.'(d02),

'Title'(d03),

'Name'(d04),

'Book.date'(d05),

'Class'(d06),

AT sy-linsz space.

ENDCASE.

*&---------------------------------------------------------------------*

*& Form DATA_OUTPUT

*&---------------------------------------------------------------------*

* List output of flight data

*----------------------------------------------------------------------*

FORM data_output.

* Loop at the internal table for writing data

LOOP AT it_flights INTO wa_flights.

* Group Level: CITYFROM

AT NEW cityfrom.

NEW-PAGE.

FORMAT COLOR COL_GROUP INTENSIFIED ON.

WRITE: / sy-vline, wa_flights-cityfrom,

AT line_size sy-vline.

FORMAT RESET.

ENDAT.

* Group Level: CITYTO

AT NEW cityto.

FORMAT COLOR COL_GROUP INTENSIFIED OFF.

WRITE: / sy-vline, wa_flights-cityto,

AT line_size sy-vline.

FORMAT RESET.

ENDAT.

* Single Record Processing

* Hotspot off, if no bookings exist

© SAP AG TAW12 19-36

IF wa_flights-seatsocc < 1.

FORMAT HOTSPOT OFF.

ELSE.

FORMAT HOTSPOT ON.

ENDIF.

* Mark international flights

FORMAT COLOR COL_KEY INTENSIFIED ON.

IF wa_flights-countryfr EQ wa_flights-countryto.

WRITE: / sy-vline, icon_space AS ICON CENTERED.

ELSE.

WRITE: / sy-vline, icon_bw_gis AS ICON CENTERED.

ENDIF.

* Data output

WRITE: wa_flights-carrid,

wa_flights-connid.

FORMAT COLOR COL_NORMAL INTENSIFIED OFF.

WRITE: wa_flights-fldate,

wa_flights-price CURRENCY wa_flights-currency,

wa_flights-currency,

wa_flights-seatsmax,

wa_flights-seatsocc,

AT line_size sy-vline.

* Hide Fields

HIDE: wa_flights-carrid, wa_flights-connid, wa_flights-fldate,

wa_flights-seatsocc.

FORMAT RESET.

* Group Level: CONNID

AT END OF connid.

SUM.

FORMAT COLOR COL_TOTAL.

WRITE: / sy-vline,

'Total'(007),

wa_flights-seatsmax UNDER wa_flights-seatsmax,

wa_flights-seatsocc UNDER wa_flights-seatsocc,

AT line_size sy-vline.

FORMAT RESET.

ENDAT.

© SAP AG TAW12 19-37

* Group Level: CITYFROM

AT END OF cityfrom.

ULINE.

ENDAT.

ENDLOOP.

ENDFORM. " DATA_OUTPUT

*&---------------------------------------------------------------------*

*& Form BOOKING_OUTPUT

*&---------------------------------------------------------------------*

* output of bookings

*----------------------------------------------------------------------*

FORM booking_output.

FORMAT COLOR COL_NORMAL.

LOOP AT it_book INTO wa_book.

WRITE: / wa_book-bookid COLOR COL_KEY,

wa_book-customid COLOR COL_KEY,

wa_book-form,

wa_book-name,

wa_book-order_date,

wa_book-class,

AT sy-linsz space.

ENDLOOP.

ENDFORM. " BOOKING_OUTPUT

*&---------------------------------------------------------------------*

*& Form BOOKING_SELECT

*&---------------------------------------------------------------------*

* selection of booking data

*----------------------------------------------------------------------*

FORM booking_select.

REFRESH it_book.

* Selection via SELECT SINGLE

* SELECT bookid customid class order_date FROM sbook

© SAP AG TAW12 19-38

* INTO CORRESPONDING FIELDS OF wa_book

* WHERE carrid = wa_flights-carrid

* AND connid = wa_flights-connid

* AND fldate = wa_flights-fldate.

* SELECT SINGLE name form telephone FROM scustom

* INTO CORRESPONDING FIELDS OF wa_book

* WHERE id = wa_book-customid.

* APPEND wa_book TO it_book.

* ENDSELECT.

* Selection via INNER JOIN

SELECT bookid customid class order_date

FROM sbook INNER JOIN scustom

ON sbook~customid = scustom~id

INTO CORRESPONDING FIELDS OF TABLE it_book

WHERE carrid = wa_flights-carrid

AND connid = wa_flights-connid

AND fldate = wa_flights-fldate.

ENDFORM. " BOOKING_SELECT

*&---------------------------------------------------------------------*

*& Form CARRIER_OUTPUT

*&---------------------------------------------------------------------*

* selection and output of carrier data

*----------------------------------------------------------------------*

FORM carrier_output.

* Local Variables

DATA: pos_col LIKE sy-cucol.

* get scarr data

SELECT SINGLE carrname currcode INTO (carrname, currcode)

FROM scarr WHERE carrid = wa_flights-carrid.

WRITE: / 'Airline:'(d11), carrname,

/ 'Airline code:'(d12), wa_flights-carrid,

/ 'Local currency:'(d13), currcode.

* Calculate the column position

pos_col = sy-cucol + 3.

* set window

© SAP AG TAW12 19-39

WINDOW STARTING AT pos_col sy-curow.

*&---------------------------------------------------------------------*

*& Include BC405_ILBS_2TOP *

*& *

*&---------------------------------------------------------------------*

REPORT sapbc405_ilbs_2 LINE-SIZE 100 NO STANDARD PAGE HEADING.

* Include for using icons

INCLUDE <icon>.

* Linetype of internal table

TYPES: BEGIN OF linetype,

cityfrom LIKE spfli-cityfrom,

cityto LIKE spfli-cityto,

carrid LIKE spfli-carrid,

connid LIKE spfli-connid,

countryfr LIKE spfli-countryfr,

countryto LIKE spfli-countryto,

fldate LIKE sflight-fldate,

price LIKE sflight-price,

currency LIKE sflight-currency,

seatsmax LIKE sflight-seatsmax,

seatsocc LIKE sflight-seatsocc,

END OF linetype.

* Constants for writing position

CONSTANTS: pos_c1 TYPE i VALUE 6,

pos_c3 TYPE i VALUE 30,

pos_c4 TYPE i VALUE 58,

pos_c5 TYPE i VALUE 68,

line_size TYPE i VALUE 100.

* Constant for CASE statement

CONSTANTS mark VALUE 'X'.

* Internal table like DDIC view DV_FLIGHTS

* DATA: it_flights LIKE TABLE OF dv_flights,

* wa_flights LIKE dv_flights.

© SAP AG TAW12 19-40

* Internal table type linetype

DATA: it_flights TYPE STANDARD TABLE OF linetype,

wa_flights TYPE linetype.

* Work area and itab for bookings

DATA: BEGIN OF wa_book,

bookid LIKE sbook-bookid,

customid LIKE sbook-customid,

class LIKE sbook-class,

order_date LIKE sbook-order_date,

name LIKE scustom-name,

form LIKE scustom-form,

END OF wa_book,

it_book LIKE TABLE OF wa_book.

* Variables for cursor position and output

DATA: field_name(30),

carrname LIKE scarr-carrname,

currcode LIKE scarr-currcode.

* Selections for connections

SELECTION-SCREEN BEGIN OF BLOCK conn WITH FRAME TITLE text-tl1.

SELECT-OPTIONS: so_car FOR wa_flights-carrid,

so_con FOR wa_flights-connid.

SELECTION-SCREEN END OF BLOCK conn.

* Selections for flights

SELECTION-SCREEN BEGIN OF BLOCK flight WITH FRAME TITLE text-tl2.

SELECT-OPTIONS so_fdt FOR wa_flights-fldate NO-EXTENSION.

SELECTION-SCREEN END OF BLOCK flight.

* Output parameter

SELECTION-SCREEN BEGIN OF BLOCK param

WITH FRAME TITLE text-tl3.

SELECTION-SCREEN BEGIN OF BLOCK radio WITH FRAME.

PARAMETERS: all RADIOBUTTON GROUP rbg1,

national RADIOBUTTON GROUP rbg1,

internat RADIOBUTTON GROUP rbg1 DEFAULT 'X'.

SELECTION-SCREEN END OF BLOCK radio.

PARAMETERS country LIKE wa_flights-countryfr.

SELECTION-SCREEN END OF BLOCK param.

© SAP AG TAW12 20-1

SAP AG 2002

l SAP Grid Control - Standard Application

l Preview of Other Techniques

Contents:

SAP Grid Control

© SAP AG TAW12 20-2

SAP AG 2002

l Explain how the SAP Grid Control collects and formats data

l Name the standard functions

l Explain how the control can be used for basic interactive reporting

At the conclusion of this unit, you will be able to:

SAP Grid Control: Unit Objectives

© SAP AG TAW12 20-3

SAP AG 2002

SAP Grid Control

SAP Grid Control: Simple ApplicationSAP Grid Control: Simple Application

More Complex TechniquesMore Complex Techniques

OutlookOutlook

© SAP AG TAW12 20-4

SAP AG 2002

Controls:Technical Background I

SAP Grid Control: What are controls?

l Independent binary software components

l Installed locally on the frontend using SAPGUI

l Move functions from the application server to the frontend

l Have a wrapper class in ABAP Objects

l Intended for reuse

n This task is performed by the SAP Control Framework.

n The R/3 System allows you to create custom controls using ABAP Objects. The application server is the Automation Client, which drives the custom controls (automation server) at the frontend.

n If custom controls are to be included on the frontend, then the SAPGUI acts as a container for them. Custom controls can be ActiveX Controls or JavaBeans.

n The system uses a Remote Function Call (RFC) to transfer methods for creating and using a control to the front end.

n ABAP objects are used to implement the controls in programs.

© SAP AG TAW12 20-5

SAP AG 2002

Controls:Technical Background II

Area

Custom container control

SAP Grid Control

Every control that you want to display on the screen must be allocated to a container control. The diagram to the left shows how a custom container control is used to integrate an SAP grid control. A container defined in the Screen Painter must be used to define an area that the custom container control is supposed to fill.

n An SAP Container can contain other controls (for example, SAP Grid Control, Tree Control, SAP Picture Control, SAP Splitter Control, and so on). The SAP Container administers these controls logically in one collection and provides a physical area for the display.

n Every control exists in a container. Since containers are themselves controls, they can be nested within one another. The container becomes the parent of its control. SAP containers are divided into five groups:

SAP custom container: Displays within an area defined in Screen Painter on screens or subscreens. Class: CL_GUI_CUSTOM_CONTAINER

SAP dialog box container: Displays in a modeless dialog box or as a full screen. Class: CL_GUI_DIALOGBOX_CONTAINER

SAP docking container: Displays as docked, resizable sub-window with the option of displaying it as a modeless dialog box. Class: CL_GUI_DOCKING_CONTAINER

SAP splitter container: Displays and groups several controls in one area - that is, splits the area into cells Class: CL_GUI_SPLITTER_CONTAINER

SAP easy splitter container: Displays controls in two cells, which the user can resize using a split bar. Class: CL_GUI_EASY_SPLITTER_CONTAINER.

© SAP AG TAW12 20-6

SAP AG 2002

SAP Example and Standard Functions

17

64

AAAAAAAALHLHLHLHLH

1717

400

402

400400

402

2000-01-172000-02-202000-03-112000-05-192000-01-132000-02-262000-03-212000-03-042000-05-28

USDUSDUSDUSDDEMDEMDEMDEMDEM

513.69

1234.561234.56

513.69513.69369.00

1234.561234.56

1234.56

A321

747-400

A310-300

A319A319

A310-300A310-300

A321

747-400

Details

Sort

Find

Filter

Total

Print

Download

Display variant

Toolbar

n Within the control, you can manually make the columns wider and narrower or use the AutoFit function. You can also rearrange the columns by dragging a selected column to the new position.

n Standard functions are available in the control toolbar. The detailed display appears as a modal dialog box containing all the fields in the row (including hidden ones) at the current cursor position.

n The ALV control supports the Sort function for any number of columns. You can define complex sort criteria and sort the columns in ascending or descending order.

n You can use the Find function to search for a string in rows or columns within a selected area (wildcard search does not require *).

n You can calculate totals for one or more numerical columns. You can then use the Subtotals function to set up control level lists. Select the columns (non-numeric fields only) to calculate and the system displays the appropriate control level totals.

n When you print or download, the system always processes the complete list, not just the displayed screen sections.

n You can define display variants to meet your own specific requirements. Saving variants: See Other Techniques

© SAP AG TAW12 20-7

SAP AG 2002

Collect data in an internal table

Field description• Field catalog• DIC Structure

SAP Grid Control: Principle

SAP GRID CONTROL Data source

SELECT ...

GET ...

Query

QuickView

List

Display data from internal table

according to field description and

standard functions like sorting and totals

Interface

n The SAP grid control is a generic tool for displaying lists in screens. The control offers standard functions such as sorting by any column, adding numeric columns, and fixed lead columns

n Data collection is performed in the program using SELECT statements or GET eventsse. The data records are saved in an internal table and passed on to the SAP control along with a field description.

n The field description contains information about the characteristics of each column, such as the column header and output length. This information can defined either globally in the Dictionary (structure in the Dictionary) or in the field catalog in the program itself. You can also merge both techniques.

n The SAP link is a standard function of Query and QuickViewer. If multiline queries or QuickView lists have been defined, they will automatically compress into a single line and output in the SAP control as a long, single line list.

© SAP AG TAW12 20-8

SAP AG 2002

The Inheritance Hierarchy of the SAP Grid Control

CL_GUI_OBJECT

CL_GUI_CONTROL

CL_GUI_ALV_GRID_BASE

CL_GUI_ALV_GRID

n The inheritance hierarchy for the class CL_GUI_ALV_GRID is shown above. n This class encapsulates communication with the instance on the presentation server, along with many

other functions. For this reason, you should instantiate this class, not its superclass.

© SAP AG TAW12 20-9

SAP AG 2002

Implementing the Control: Screen

Create layout in Screen PainterC

Create in Menu Painter:Status

100

Create in Screen Painter:Screen 100

In the flow logic of screen 100

PBO Define statusPAI OK_CODE processing for BACK, EXIT, and CANCEL

MY_CONTROL_AREA

n Use Screen Painter to create a container for the SAP grid control. The control requires an area where it can be displayed in the screen. You have to create a container control that determines this area.

n Use the corresponding icon in the Screen Painter layout to create the container control. The size of area MY_CONTROL_AREA determines the subsequent size of the SAP control.

n A dialog status with the standard BACK, EXIT, and CANCEL functionality must be set during the PBO event. You must also add the necessary coding for these function codes in the PAI event.

© SAP AG TAW12 20-10

SAP AG 2002

Implementation in the Program

* CONTROLSDATA: g_custom_container

TYPE REF TO cl_gui_custom_container,sap_grid TYPE REF TO cl_gui_alv_grid.

Container control

SAP Grid Control

SAP grid control can be displayed using class CL_GUI_ALV_GRID.

n The reference variables for the custom container and the ALV grid control must be declared. n To create reference variables, use ABAP statement TYPE REF TO <class name>. n The global classes you need to do this are called cl_gui_custom_container (for the custom container

control) and cl_gui_alv_grid (for the SAP grid control). n The global classes are defined in the Class Builder. You can use the Class Builder to display

information for the methods, their parameters, exceptions, and so on.

© SAP AG TAW12 20-11

SAP AG 2002

Generating and Linking Objects

MODULE create_objects OUTPUT.

IF g_custom_container IS INITIAL.

CREATE OBJECTCREATE OBJECT g_custom_containerEXPORTING container_name = 'MY_CONTROL_AREA'.

CREATE OBJECTCREATE OBJECT sap_gridEXPORTING i_parent = g_custom_container.

ENDIF.

ENDMODULE. " CREATE_OBJECTS OUTPUT

CREATE OBJECTCREATE OBJECT

CREATE OBJECTCREATE OBJECT C

n Use ABAP statement CREATE OBJECT <name> to create the objects for the container and the ALV control. Objects are instances of a class.

n When an object is created (CREATE), method CONSTRUCTOR of the corresponding class is executed. The parameters of method CONSTRUCTOR determine which parameters have to be supplied with data when the object is created. In the above example, object sap_grid is given the name of the container control (g_custom_container) in exporting parameter i_parent, which links the two controls. For information on which parameters method CONSTRUCTOR possesses and which of these parameters are required, see the Class Builder.

n Objects should only be created once during the program. To ensure that this is the case, enclose the CREATE OBJECT statement(s) in an IF <object_name> IS INITIAL. ... ENDIF clause. The objects must be generated before the control is displayed for the first time - that is, during the PBO event of the ALV subscreen container.

© SAP AG TAW12 20-12

SAP AG 2002

Program Flow

START-OF-SELECTION

SELECT * FROM

Field catalogitab_sflight

Internal table with data Description of columns

A B CABC

A B C

sflight ...

sflight

DIC

CALL SCREEN 100.

Process Before Output Process After Input

MODULE status_0100.

MODULE create_objects.

MODULE transfer_data.

MODULE exit AT EXIT-COMMAND.

MODULE user_command_0100.

n To display the requested dataset in the SAP Grid Control, the data must be passed on to the control as an internal table, and a field description must exist indicating the order in which the columns will be output.

n In the simplest case, the field description can use a structure from the Dictionary. The Dictionary also determines the technical field attributes like type and length, as well as the semantic attributes like short and long texts. The SAP Grid Control uses this information to determine the column widths and headers. The column sequence is determined by the field sequence in the structure.

n If no suitable structure is active in the Dictionary, or you want to output internal program fields in the control, then you will have to define information like the output length and column header in the field catalog.

n In a typical report application, the data is read first using SELECT...INTO TABLE or using a logical database and then APPEND/INSERT the data into an internal table. When the data retrieval is complete, the ABAP statement CALL SCREEN <number> is used to call the screen containing the SAP Grid Control.

© SAP AG TAW12 20-13

SAP AG 2002

Displaying the Data in the Control

MODULE transfer_data OUTPUT.

CALL METHODCALL METHOD sap_grid->set_table_for_first_displayEXPORTING i_structure_name = 'SFLIGHT'CHANGING it_outtab = itab_sflight.

ENDMODULE. " TRANSFER_DATA OUTPUT

Process Before Output

MODULE status_0100.

MODULE create_objects.

MODULE transfer_data.

SET_TABLE_FOR_FIRST_DISPLAY is a method of classCL_GUI_ALV_GRID.

CALL METHODCALL METHOD

n The data transfer to the ALV control takes place during the call of method set_table_for_first_display from class cl_gui_alv_grid. The method call must be programmed at the PBO event of the screen with the SAP Grid Control container.

n The name of the Dictionary structure that supplies the field description is specified in exporting parameter i_structure_name. The name of the internal table that contains the data records to display is specified in changing parameter it_outtab.

© SAP AG TAW12 20-14

SAP AG 2002

SAP Grid Control

SAP Grid Control: Simple ApplicationSAP Grid Control: Simple Application

More Complex TechniquesMore Complex Techniques

OutlookOutlook

© SAP AG TAW12 20-15

SAP AG 2002

Field Catalog

TYPES: BEGIN OF t_con,carrid like sflight-carrid, ... free_seat free_seat LIKE sflight-seatsmax,

(30),

END OF t_con.

DATA: gt_outtabgt_outtab type STANDARD TABLE OF t_con,...gt_fieldcat TYPE lvc_t_fcatgt_fieldcat TYPE lvc_t_fcat,

wa_fieldcat LIKE line of gt_fieldcat.Field catalog

Additional fields

Available seats

Output table

You want to output internal fields, such as available seats, in the SAP grid control

free_seatsfree_seats

icon_nameicon_name

gt_fieldcat TYPE lvc_t_fcatgt_fieldcat TYPE lvc_t_fcat,,

n The field description for the SAP Grid Control can be taken from an active Dictionary structure (fully automatic), by passing a field catalog (manual), or through a mixture of the two options (merge).

n The field catalog is in internal table with type lvc_t_fcat. This type is defined globally in the Dictionary.

n Each line in the field catalog table corresponds to a column in the SAP control.

© SAP AG TAW12 20-16

SAP AG 2002

Selected Fields in the Field Catalog

Table type lvc_t_fcat has a global DIC definition.

• fieldname

• ref_table

• ref_field

• inttype

•outputlen

• coltext

• seltext

• col_pos

• no_out

• icon

Field name in output table

Name of DIC reference structure

Name of DIC reference field

Data type (c, f, i, ...)

Column width

Column header

Field name in detail view

Column position

Column hidden

Output columns as icon

n The field characteristics (= column characteristics) are defined in the field catalog. The field catalog is in internal table with type lvc_t_fcat. Each line that is explicitly described in the ALV control corresponds to a column in the field catalog table.

n The link to the data records to output that are saved in internal table <outtab> is established through field name <outtab-field>. This name must be specified in column fieldname in the field catalog.

n This field can be classified through a Dictionary reference (ref_table and ref_field) or by specifying an ABAP data type (inttype).

n Column headers and field names in the detail view of an SAP control line can be determined in the field catalog in coltext and seltext, respectively.

n The position of a field during output can be determined with col_pos in the field catalog. n If you want to hide a column, fill field no_out with an X in the field catalog. Hidden fields can be

displayed again in a user display variant. n Icons can be displayed in the SAP control. If you want a column to be interpreted as an icon, then the

icon name must be known to the program (include <icon>.) and icon = X must be specified for this column in the field catalog.

© SAP AG TAW12 20-17

SAP AG 2002

Filling and Passing On the Field Catalog

CALL METHOD alv_grid->set_table_for_first_displayEXPORTING i_structure_name = 'SFLIGHT'CHANGING it_outtab = gt_outtab

it_fieldcatalog = gt_fieldcatit_fieldcatalog = gt_fieldcat.

CLEAR wa_fieldcat.wa_fieldcat-fieldname = 'FREE_SEATS'.wa_fieldcat-ref_table = 'SFLIGHT'.wa_fieldcat-ref_field = 'SEATSMAX'.wa_fieldcat-coltext = text-001.wa_fieldcat-seltext = text-001.wa_fieldcat-col_pos = pos_free.APPEND wa_fieldcat TO gt_fieldcat.

CLEAR wa_fieldcat.wa_fieldcat-fieldname = 'ICON_NAME'.wa_fieldcat-icon = 'X'. " Displayed as Iconwa_fieldcat-coltext = text-001.wa_fieldcat-seltext = text-001.wa_fieldcat-col_pos = pos_icon.APPEND wa_fieldcat TO gt_fieldcat.

Fill field catalog

for additional fields

it_fieldcatalog = gt_fieldcatit_fieldcatalog = gt_fieldcat.

n The above example shows a semi-automatic field description: Part of the field description comes from the Dictionary structure (sflight), while another part is explicitly defined in the field catalog (gt_fieldcat).

n The field catalog (internal table) which fills in the program, passes on together with the name of the Dictionary structure during the method call. The information merges accordingly in method set_table_for_first_display.

© SAP AG TAW12 20-18

SAP AG 2002

Grid Layout Options

ParameterI_STRUCTURE_NAME

Which parameters of the SET_TABLE_FOR_FIRST_DISPLAY method must be filled, and in which situations?

F1 F2 F3 F4 F1 F2 F3 F4Z A2 B2 B4 Z

F1 F2 F3 F4 Z A2 B2 B4 Z

F1 F2 F3 F4

A1 A2 A3

B1 B2 B3 B4

ParameterIT_FIELDCATALOG

Display in theSAP Grid Control

Data table in the calling program

Structure types in theABAP Dictionary

n Field catalogs are created in one of the following three ways depending on the line type used by the data table:

n Case 1: All the fields of the global structure type have an identically-named column in the data table. You want to display precisely these columns. In this case, you can have the proxy instance generate the field catalog. You need only pass the name of the global structure type. Data table columns are not displayed on the screen unless they are defined in the global structure type.

n Case 2: All fields of the global structure type have an identically-named column in the data table, but you want to adapt the attributes derived from the ABAP Dictionary or you want to add columns or both. In this case, you need to add lines in the field catalog matching the columns you want to add or change.

n Case 3: Either there are no Dictionary references in the line type of the data table or there are references only for some of the global structure fields. In this case, the calling program must generate the field catalog from scratch.

© SAP AG TAW12 20-19

SAP AG 2002

Saving Display Variants

* Save variantsdata: gs_variant type disvariant,

x_save.

CALL METHOD sap_grid->set_table_for_first_displayEXPORTING

i_structure_name = 'SFLIGHT'isis__variant variant = = gsgs__variantvarianti_savei_save = x_save= x_saveis_layout = gs_layout

CHANGINGit_outtab = gt_outtabit_fieldcatalog = gt_fieldcat.

* Filling variant structure* At least the report name has to be filled

gsgs__variantvariant--reportreport == sysy--repidrepid.

*Determine saving options.x_save = 'A'. "The user may save ALL types of variants

gsgs__variantvariant--reportreport == sysy--cprogcprog.

i_savei_save = x_save= x_saveisis__variant variant = = gsgs__variantvariant

n For a user to save display variants, parameters is_variant and i_save must be passed on during method call set_table_for_first_screen. To assign display variants uniquely to a program, at least the program name must be supplied in the transferred structure (gs_variant). Program names can be up to 30 characters long.

n If you only pass on the current parameters for is_variant, then existing variants can be loaded, but no new ones can be saved. If you use parameter i_save, you must pass on a variant structure with is_variant.

n I_SAVE = SPACE No variants can be saved.

n I_SAVE = 'U' The user can only save user-specific variants.

n I_SAVE = 'X' The user can only save general (shared) variants.

n I_SAVE = 'A' The user can save both user-specific and general (shared) variants.

© SAP AG TAW12 20-20

SAP AG 2002

Filling and Passing On the Layout Structure

* LayoutDATA: gs_layout TYPE lvc_s_layo.

* Filling laoyout structuregs_layout-grid_title = 'SAP Grid Title'(002).gs_layout-detailtitl = 'Detail Title'(003).gs_layout-zebra = 'X'.

CALL METHOD sap_grid->set_table_for_first_displayEXPORTING

i_structure_name = 'SFLIGHT'is_variant = gs_varianti_save = x_saveis_layoutis_layout = gs_layout= gs_layout

CHANGINGit_outtab = gt_outtabit_fieldcatalog = gt_fieldcat.

is_layoutis_layout = gs_layout= gs_layout

n You can use parameter is_layout of method set_table_for_first_display, for example, to define the header in the ALV control and the detail display.

n To do this, define a query area <gs_layout> in the program in accordance with Dictionary structure lvc_s_layo, and pass on the text to display in field <gs_layout>-grid_title or <gs_layout>-detailtitl.

n If you want to create print lists with zebra stripes, set field <gs_layout>-zebra to X. You can display a print preview for print lists by requesting standard function Print.

© SAP AG TAW12 20-21

SAP AG 2002

Interface to Display Method

CALL METHOD sap_grid->set_table_for_first_display

EXPORTING i_structure_name = Name of structure, table, or view

is_variant = Display variants

i_save = Save display variant

i_default = Select initial layout

is_layout = Change technical configuration

is_print = Parameters for printing on backend

it_special_groups = Groupings

it_toolbar_excluding = Hide standard functions

CHANGING

it_outtab = Output table

it_fieldcatalog = Field catalog

it_sort = Sort criteria for first list output

it_filter = Filter criteria for first list output

n All parameters of method SET_TABLE_FOR_FIRST_DISPLAY from global class CL_GUI_ALV_GRID are defined in the Class Builder.

© SAP AG TAW12 20-22

SAP AG 2002

SAP Grid Control

SAP Grid Control: Simple ApplicationSAP Grid Control: Simple Application

More Complex TechniquesMore Complex Techniques

OutlookOutlook

© SAP AG TAW12 20-23

SAP AG 2002

Mouse Operations

Air...AAAAAAAALHLHLHLHLH

Flug...17171764

400400400400402

Preis513,69513,69513,69369,00

1234,561234,561234,561234,561234,56

Währ...USDUSDUSDUSDDEMDEMDEMDEMDEM

Datum2000-01-172000-02-202000-03-112000-05-192000-01-132000-02-162000-03-212000-03-042000-05-28

HOTSPOT_CLICK (clicking a hot spot) Export parameters:(E_ROW_ID (line ID, type LVC_S_ROW)

< INDEX (line number in data table)( E_COLUMN (column ID, type LVC_S_COL)

< FIELDNAME (column name in data table)

DOUBLE_CLICK (double-clicking a cell or row)Export parameters:(E_ROW (line ID, type LVC_S_ROW)

< INDEX (line number in data table)( E_COLUMN (column ID, type LVC_S_COL)

< FIELDNAME (column name in data table)

n If the user double-clicks a data area, the DOUBLE_CLICK event is triggered in the calling program.

n The export parameters contain information about the data table. Note that both parameters are structures. � E_ROW:

The INDEX field contains the line number in the internal table that belongs to the double-clicked row in the data area. � E_COLUMN:

The FIELDNAME field contains the name of the column in the internal table that belongs to the double-clicked cell in the data area.

n If a column is characterized as a hot spot, the HOTSPOT_CLICK event is triggered when the user clicks this column in the data area. The export parameters are filled in a similar way to those of the DOUBLE_CLICK event.

n For further information about other mouse operation events, refer to the online documentation.

© SAP AG TAW12 20-24

SAP AG 2002

Outlook: Handling Events I

Events are defined in class CL_GUI_ALV_GRID, such as DOUBLE_CLICK

DOUBLE_CLICK.

n Events are defined in global class cl_gui_alv_grid; you can use these events to implement user interaction within the program. To respond to a double-click on a table line, you must respond to event DOUBLE_CLICK.

n You receive control in the program, allowing you to implement interactive reporting - such as a full-screen details list. The events for cl_gui_alv_grid are located in the Class Builder.

© SAP AG TAW12 20-25

SAP AG 2002

Outlook: Handling Events II

CLASS lcl_ils DEFINITION.PUBLIC SECTION.METHODS on_dblclick FOR EVENT double_click

OF cl_gui_alv_grid IMPORTING e_row.ENDCLASS.

CLASS class lcl_ils IMPLEMENTATION.METHOD on_dblclick .

[ own functionality ].

ENDMETHOD.ENDCLASS.

Definition of a local class

Implementing a localclass with handler

method

DATA alv_dblclick TYPE REF TO lcl_ils.

CREATE OBJECT sap_dblclick.

SET HANDLER sap_dblclick->on_dblclick FOR alv_grid.

Generating the object

Registration ofhandler method

for event double_click

n To define and implement a local class in the program, you use a handler method. In this handler method, you program the functionality to trigger by a double-click in the output table.

n To activate a handler method at runtime, a class or an object from that class registers itself with an event using command SET HANDLER. The names of the IMPORTING parameters in the handler method correspond to the names of the EXPORTING parameters of the related event.

n In the above example, the local class is LCL_ILS and the handler method is ON_DBLCLICK. An object - SAP_DBLCLICK - is created and registers itself for event DOUBLE_CLICK.

n You can query parameter e_row-index to determine which output line was requested by the double-click. This parameter corresponds to the line number of the output table (internal table with the data records to output). If you need information for the selected line, you have to read it with READ TABLE itab INDEX e_row-index.

n This subsequent read in the output table generally corresponds to the HIDE area in conventional reporting. You first have to make sure that the user has double-clicked a line in the output table (similar to the valid line selection with the HIDE technique).

© SAP AG TAW12 20-26

SAP AG 2002

Demo Programs Delivered for the SAP Grid Control

BCALV_GRID_01

BCALV_GRID_02

BCALV_GRID_03

BCALV_GRID_04

BCALV_GRID_05

BCALV_GRID_06

BCALV_GRID_07

BCALV_GRID_08

BCALV_GRID_09

BCALV_GRID_10

Print list events

Basic and detail lists with an instance

Detail list in a modal dialog box

Threshold value handling (exceptions/traffic light icons)

Adding your own functions to the application toolbar

Context menus

Adding your own menus to the application toolbar

Menu with standard pushbutton

Options for managing display variants

Initial use of display variants

SLIS

Package Programs Demonstrates

n As well as these demonstration and test programs, you will also find other Repository objects for the SAP Grid Control in the SLIS package.

n This package is part of the standard SAP R/3 System - that is, it is always delivered with the ABAP Workbench.

n You can also analyze and execute these and other demonstration and test programs in a comfortable test environment. In the ABAP Workbench, choose Environment → Examples → Control examples.

© SAP AG TAW12 20-27

SAP AG 2002

l Explain how the SAP Grid Control collects and formats data

l Name the standard functions

l Explain how the control can be used for basic interactive reporting

You are now able to:

ALV Grid Control: Unit Summary

© SAP AG TAW12 20-28

Exercises

Unit: ALV Grid Control

Topic: Using the ALV Grid Control to Output a List

When you have completed these exercises, you will be able to:

• Use the applications of the ALV grid control

1-1 Copy template SAPBC405_ALVT_1 to program Z##ALV1_... . Copy all the program objects (including screens, GUI status, and so on). Sample solution for exercise: SAPBC405_ALVS_1.

The OK code processing for screen 100 is included in the template (BACK, EXIT, CANCEL). Do not work in the Screen Painter.

All the necessary program objects are contained in the TOP include.

1-1-1 Familiarize yourself with the program.

2-1 Read data from table SFLIGHT and display the data on screen 100 in an ALV grid control.

2-1-1 Calculate the number of free seats.

2-1-2 Include the following fields in the ALV control:

carrid, connid, fldate, price, planetype, seatsmax, seatsocc, paymentsum, free_seats.

Use the method SET_TABLE_FOR_FIRST_DISPLAY of class CL_GUI_ALV_GRID.

2-1-3 Place the field free_seats in position 10 and make sure that the column is colored (for example, colour 3, intensified display).

3-1 Change the layout.

3-1-1 Enter a title in the control and the detail view. Use text elements so that the text can be translated.

3-1-2 Create a striped pattern (zebra).

© SAP AG TAW12 20-29

Solutions

Unit: ALV Grid Control

Topic: Using the ALV Grid Control to Output a List

*&---------------------------------------------------------------------*

*& SAPBC405_ALVS_1 *

*& *

*&---------------------------------------------------------------------*

*& *

*& *

*&---------------------------------------------------------------------*

INCLUDE bc405_alvs_1top.

*&---------------------------------------------------------------------*

*& Event START-OF-SELECTION

*&---------------------------------------------------------------------*

START-OF-SELECTION.

SELECT * FROM sflight INTO CORRESPONDING FIELDS OF wa_outtab

WHERE carrid IN so_car.

wa_outtab-free_seats = wa_outtab-seatsmax - wa_outtab-seatsocc.

APPEND wa_outtab TO gt_outtab.

ENDSELECT.

CALL SCREEN 100.

*&---------------------------------------------------------------------*

*& Module STATUS_0100 OUTPUT

*&---------------------------------------------------------------------*

* text

*----------------------------------------------------------------------*

MODULE status_0100 OUTPUT.

SET PF-STATUS 'S100'.

SET TITLEBAR 'T100'.

ENDMODULE. " STATUS_0100 OUTPUT

*&---------------------------------------------------------------------*

*& Module EXIT INPUT

© SAP AG TAW12 20-30

*&---------------------------------------------------------------------*

* text

*----------------------------------------------------------------------*

MODULE exit INPUT.

LEAVE PROGRAM.

ENDMODULE. " EXIT INPUT

*&---------------------------------------------------------------------*

*& Module USER_COMMAND_0100 INPUT

*&---------------------------------------------------------------------*

* text

*----------------------------------------------------------------------*

MODULE user_command_0100 INPUT.

MOVE ok_code TO save_ok_code.

CLEAR ok_code.

CASE save_ok_code.

WHEN 'BACK'.

CALL METHOD g_custom_container->free.

LEAVE TO SCREEN 0.

WHEN 'EXIT'.

CALL METHOD g_custom_container->free.

LEAVE TO SCREEN 0.

ENDCASE.

ENDMODULE. " USER_COMMAND_0100 INPUT

*&---------------------------------------------------------------------*

*& Module CREATE_OBJECTS OUTPUT

*&---------------------------------------------------------------------*

* text

*----------------------------------------------------------------------*

MODULE create_objects OUTPUT.

IF g_custom_container IS INITIAL.

CREATE OBJECT g_custom_container

EXPORTING container_name = 'MY_CONTROL_AREA'.

CREATE OBJECT alv_grid

EXPORTING i_parent = g_custom_container.

ENDIF.

ENDMODULE. " CREATE_OBJECTS OUTPUT

*&---------------------------------------------------------------------*

© SAP AG TAW12 20-31

*& Module TRANSFER_DATA OUTPUT

*&---------------------------------------------------------------------*

* text

*----------------------------------------------------------------------*

MODULE transfer_data OUTPUT.

CALL METHOD alv_grid->set_table_for_first_display

EXPORTING

i_structure_name = 'SFLIGHT'

is_layout = gs_layout

CHANGING

it_outtab = gt_outtab

it_fieldcatalog = gt_fieldcat.

ENDMODULE. " TRANSFER_DATA OUTPUT

*&---------------------------------------------------------------------*

*& Module FIELD_CATALOG OUTPUT

*&---------------------------------------------------------------------*

* text

*----------------------------------------------------------------------*

MODULE field_catalog OUTPUT.

CLEAR wa_fieldcat.

wa_fieldcat-fieldname = 'FREE_SEATS'.

wa_fieldcat-ref_table = 'SFLIGHT'.

wa_fieldcat-coltext = 'Free seats'(001).

wa_fieldcat-seltext = 'Free seats'(001).

wa_fieldcat-col_pos = pos_free.

wa_fieldcat-emphasize = 'C310'.

APPEND wa_fieldcat TO gt_fieldcat.

ENDMODULE. " FIELD_CATALOG OUTPUT

*&---------------------------------------------------------------------*

*& Module LAYOUT OUTPUT

*&---------------------------------------------------------------------*

* text

*----------------------------------------------------------------------*

MODULE layout OUTPUT.

© SAP AG TAW12 20-32

gs_layout-grid_title = 'ALV Grid Title'(002).

gs_layout-detailtitl = 'Detail Title'(003).

gs_layout-zebra = 'X'.

ENDMODULE. " LAYOUT OUTPUT

*&---------------------------------------------------------------------*

*& Include BC405_ALVS_1TOP *

*& *

*&---------------------------------------------------------------------*

PROGRAM sapbc405_alvs_1 .

TYPES: BEGIN OF t_con,

carrid LIKE sflight-carrid,

connid LIKE sflight-connid,

fldate LIKE sflight-fldate,

price LIKE sflight-price,

currency LIKE sflight-currency,

planetype LIKE sflight-planetype,

seatsmax LIKE sflight-seatsmax,

seatsocc LIKE sflight-seatsocc,

paymentsum LIKE sflight-paymentsum,

free_seats LIKE sflight-seatsmax,

END OF t_con.

* OK code handling

DATA: ok_code LIKE sy-ucomm,

save_ok_code LIKE sy-ucomm.

* Data, which will be displayed in the ALV Control

DATA: gt_outtab TYPE STANDARD TABLE OF t_con,

wa_outtab TYPE t_con.

* Field position

DATA: pos_free TYPE i VALUE 10.

* Fieldcatalog

DATA: gt_fieldcat TYPE lvc_t_fcat,

wa_fieldcat LIKE LINE OF gt_fieldcat.

© SAP AG TAW12 20-33

* Layout

DATA: gs_layout TYPE lvc_s_layo.

* CONTROLS

DATA: g_custom_container TYPE REF TO cl_gui_custom_container,

alv_grid TYPE REF TO cl_gui_alv_grid.

* Selection Screen

SELECTION-SCREEN BEGIN OF BLOCK connection WITH FRAME.

SELECT-OPTIONS: so_car FOR wa_outtab-carrid.

SELECTION-SCREEN END OF BLOCK connection.

© SAP AG TAW12 21-1

SAP AG 2002

Appendix

Contents:

l Additional slides

© SAP AG TAW12 21-2

SAP AG 2002

Appendix

Additional slidesAdditional slides

© SAP AG TAW12 21-3

SAP AG 2002

Calling an LDB with a Function Module

Function module LDB_PROCESS

* Start of Logical DatabaseCALL FUNCTION 'LDB_PROCESS'EXPORTINGldbname = 'F1S'

* VARIANT =* EXPRESSIONS =* FIELD_SELECTION =

TABLEScallback = call_back_tabselections = sel_tab.

CALL FUNCTION 'LDB_PROCESS'CALL FUNCTION 'LDB_PROCESS'LDB does not have to be entered in the program attributes

Several LDBs can be used in a single program

LDBs are also available in interactive reporting

The same LDB can be called several times in a program

n Previously, logical databases (LDB) could only be used in executable programs. To do this, the name of the logical database had to be entered in the program attributes for the GET events to be available to the program. In particular, this means that logical databases could not be used for interactive reporting or module pools. Starting in Release 4.5, a logical database can be processed using function module LDB_PROCESS.

n Function module LDB_PROCESS can be used to call each logical database exactly one time. If you need to process the same logical database several times over the course of the program, you have to modify the database program for this functionality.

n A multiple call is not involved when the logical database is entered in the program attributes. The LDB can then be called again with function module LDB_PROCESS.

© SAP AG TAW12 21-4

SAP AG 2002

Using Callback Form Routines

REPORT sapbc405_ldbd_ldb_process.

SFLIGHT

SBOOK

FORM PUT_SPFLI.SELECT * FROM SPFLI ...PUT SPFLI.ENDSELECT.

ENDFORM.

FORM PUT_SFLIGHT.SELECT * FROM SFLIGHT .PUT SFLIGHT.ENDSELECT.

ENDFORM.

FORM PUT_SBOOK.SELECT * FROM SBOOK ...PUT SBOOK.ENDSELECT.

ENDFORM.

Structure of F1SStructure of F1S

PUT SBOOK.PUT SBOOK.

PUT SPFLI.PUT SPFLI.

PUT SFLIGHT.PUT SFLIGHT.

PROGRAM SAPDBF1SDEFINING DATABASE F1S.

...

USING name LIKE ldbn-ldbnode workarea TYPE spflimode TYPE cselected TYPE c.

FORM call_back_FORM call_back_spflispfli

USING name LIKE ldbn-ldbnode workarea TYPE sflight mode TYPE cselected TYPE c.

FORM call_back_FORM call_back_sflightsflight

USING name LIKE ldbn-ldbnode workarea TYPE sbookmode TYPE cselected TYPE c.

FORM call_back_FORM call_back_sbooksbook

CALL FUNCTION 'LDB_PROCESS' ...CALL FUNCTION 'LDB_PROCESS' ...

FORM LDB_PROCESS_INIT.LDB_SUBRC = 0.

ENDFORM. Multiple call

SPFLI

n In principle, the interaction between the logical database and function module LDB_PROCESS is analogous to the interaction during GET events. You pass on the name of the LDB to call when you call the function module.

n An internal table and a table work area have to be created in accordance with Data Dictionary structure ldbcb. This table collects the nodes to process and the names of the callback subroutines, which are passed on during the function module call. The individual table fields have the following meanings:

� LDBNODE Name of the node to process

� GET X Process the GET event of the above node

� GET_LATE X Process the GET LATE event of the above node

� CB_PROG Name of the program containing the callback subroutine

� CB_FORM Name of the callback subroutine

n When you call the logical database, you have to make sure that the selection screen is supplied with valid values. An internal table and a table work area have to be created in accordance with Data Dictionary structure ldbcb. This table is used to pass the selection criteria on to the logical database.

n To enable a logical database for multiple processing, you have to add subroutine LDB_PROCESS_INIT to the database program.

© SAP AG TAW12 21-5

SAP AG 2002

Checking Internal Program Selections

REPORT sapbc405_ldbd_ldb_process_sel.

SELECT-OPTIONS: sdepart FOR spfli-deptimeDEFAULT '08000' TO '230000',sprice FOR sflight-price DEFAULT '500' TO '1000'.

...FORM call_back_sflight

USING name LIKE ldbn-ldbnode workarea TYPE sflight mode TYPE cselected TYPE c.

* check of selection criteria sprice IF NOT workarea-price IN sprice.

selected = space.EXIT.

ENDIF.

SELECTSELECT--OPTIONS:OPTIONS:

selected = space

Selections

Dep. time 08:00:00 23:00:00

Price 500.00 1000.00

Are dynamic selectionsallowed in this table?

SPFLI YES

SFLIGHT NO

Negative CHECK

Positive CHECKSBOOK SBOOK

SFLIGHT SFLIGHT

IF NOTIF NOT workareaworkarea--price INprice IN spricesprice..

n If you specify a logical database in your program with function module LDB_PROCESS and declare additional selections in the program attributes that refer to the fields of a node not designated for dynamic selection, the program must contain a check as to whether the current data record fulfills the selection criteria.

n If the check fails, you have to set parameter selected in the subroutine to space to ensure that deeper hierarchy nodes are not processed.