Sie sind auf Seite 1von 60

SAP TechEd 08

COMP361
Advanced ABAP Programming

Frank Bertelsmeier, NW F ABAP Daniel Housmans, NW Technical Consulting Sigrid Wortmann, NW F ABAP

Disclaimer

This presentation outlines our general product direction and should not be relied on in making a purchase decision. This presentation is not subject to your license agreement or any other agreement with SAP. SAP has no obligation to pursue any course of business outlined in this presentation or to develop or release any functionality mentioned in this presentation. This presentation and SAP's strategy and possible future developments are subject to change and may be changed by SAP at any time for any reason without notice. This document is provided without a warranty of any kind, either express or implied, including but not limited to, the implied warranties of merchantability, fitness for a particular purpose, or non-infringement. SAP assumes no responsibility for errors or omissions in this document, except if such damages were caused by SAP intentionally or grossly negligent.

SAP 2008 / SAP TechEd 08 / COMP361 Page 2

SAP TechEd 08

Learning Objectives

As a result of this workshop, you will be able to:


Deploy strings for efficient handling of text-based information Make use of regular expressions to process strings effectively Write compact code by using extended expression capabilities Utilize string templates to create formatted text Work proficiently and efficiently with the new features for internal tables Implement generic services by using dynamic WHERE conditions Optimize the performance of your programs using secondary keys

Benefit from new ABAP features of SAP NetWeaver 7.10 and 7.11

SAP 2008 / SAP TechEd 08 / COMP361 Page 3

Agenda

1. Efficient Processing of Textual Data 1.1. Recab: String Data Types


1.2. Regular Expressions

2. Extended Expressions
2.1. Enhanced Expression Capabilities 2.2. String Expressions

3. New Features of Internal Tables


3.1. Dynamic WHERE Condition 3.2. Secondary Keys

SAP 2008 / SAP TechEd 08 / COMP361 Page 4

SAP TechEd 08

Sequential Data Types in ABAP

Business information = sequences of characters or bytes


Customer names, addresses Product numbers, dates, currencies XML data Natural language

Overview of data types in ABAP representing character and byte sequences Character Special Byte

Fixed Size

D,

T,

Variable Size

STRING

XSTRING

SAP 2008 / SAP TechEd 08 / COMP361 Page 5

Comparison of Strings and Fixed-Sized Fields

Strings Length adjusted dynamically at runtime Max length of 2,000,000,000 bytes Trailing blanks are significant Backquote literals `stringlit` Substring idiom +offset(length) for read access only

Fields Length fixed and preallocated Max length of 262.143 chars Trailing blanks are ignored Straight quote literals 'fieldlit' Subfield idiom +offset(length) for read and write access

Some benefits that ABAP strings provide


Efficient

management of string storage space garbage collection Automatic value sharing with copy-on-write
Automatic
SAP 2008 / SAP TechEd 08 / COMP361 Page 6

SAP TechEd 08

Strings Values

String values are stored separately from variables in memory


DATA: BEGIN OF struc1, a(3) TYPE n, b(10) TYPE c, c(3) TYPE n, END OF struc1. struc1 is flat
1 2 3 A B C D E F G H I J 4 5 6 a b c

DATA: BEGIN OF struc2, a(3) TYPE n, b TYPE string, c(3) TYPE n, END OF struc2. struc2 is deep
1 2 3 string reference 4 5 6 a b c
string value

Decoupling of value and reference allows


Efficient Sharing

A B C D E F G H I J

resizing of strings of string values

SAP 2008 / SAP TechEd 08 / COMP361 Page 7

String Storage Allocation

Memory allocation during a typical program run


DATA str TYPE string.
string reference (8 bytes) string header (16-32 bytes)

str = 'first'.
f i r s t

string value (variable)

str = 'second value'. SHIFT str BY 5 PLACES. str = 'another try'.

d a s

e n

v o c

a o t

n h l

u d e

e r

a t

r l

u y

str = 'a final value!'.

main memory
SAP 2008 / SAP TechEd 08 / COMP361 Page 8

SAP TechEd 08

String Sharing

Values may be shared by multiple string references


DATA: str1 TYPE string, str2 TYPE string, str3 TYPE string. str1 = 'common'. str2 = str1. str3 = str2.
c o m m o n str1 str2 str3

references + headers

SHIFT str2 BY 4 PLACES.

Unsharing copy-on-write / lazy copy


Delays

costly copying as long as possible

SAP 2008 / SAP TechEd 08 / COMP361 Page 9

Restrictions on Substrings

Substring idiom +offset(length) cannot be used to modify strings


DATA str TYPE string VALUE `strvalue`. WRITE / str+3(4). str+3(4) = `x`.
Use

" OK " would modify value

REPLACE statement (or replace function) instead

REPLACE SECTION OFFSET 3 LENGTH 4 OF str WITH `x`.

Field symbols cannot be used for substring access


Value

changes would necessitate updating all assigned field symbols

FIELD-SYMBOLS <fs> TYPE any. ASSIGN str+3(4) TO <fs>. SHIFT str RIGHT BY 2 PLACES.
SAP 2008 / SAP TechEd 08 / COMP361 Page 10

" shifts char positions

SAP TechEd 08

Which Data Type to Choose

Advantages of character fields


to access (+off(len), flat structures) No internal overhead for accessing value
Easy

Advantages of strings
Storage

allocated dynamically

DATA custname TYPE c LENGTH ??. READ DATASET dset INTO line.
Common

values are shared

DATA customers TYPE TABLE OF cust_record. " cust_record = ( name, street, city )
Trailing

blanks are significant (may increase performance)


Checks 75 trailing blanks for finding end of text

DATA c80 TYPE c LENGTH 80 VALUE 'hello'. CONCATENATE c80 'world' INTO c80.
SAP 2008 / SAP TechEd 08 / COMP361 Page 11

Agenda

1. Efficient Processing of Textual Data


1.1. Recab: String Data Types

1.2. Regular Expressions 2. Extended Expressions


2.1. Enhanced Expression Capabilities 2.2. String Expressions

3. New Features of Internal Tables


3.1. Dynamic WHERE Condition 3.2. Secondary Keys

SAP 2008 / SAP TechEd 08 / COMP361 Page 12

SAP TechEd 08

Ubiquitous Text Processing

Checking

input for validity: Is credit card number well-formatted?


1234 5678 1234 5678 1234 5678 1234 5AB8

1234-5678-1234-5678
Extracting

information from text: What is the document ID requested by the web client?
http://sap.com/&user=frank&id=1234&lang=EN

Normalizing

values: Eliminate non-digits in phone number for data export


+49 (6227) 7-47474 496227747474

SAP 2008 / SAP TechEd 08 / COMP361 Page 13

Improving Text Processing With REs

Regular Expressions (REs, regexes) provide powerful pattern language for text processing
Well

understood Developed by mathematician Kleene in the 1950s Powerful Highly focused special purpose language Many common text processing tasks turn into simple one-liners Standardized and widely used Made popular by Unix tools: grep, sed, awk, emacs Built into some languages like Perl and Java; add-on libraries available for many others

Stephen C. Kleene Image U. of Wisconsin

Early Unix de-facto standard formalized in PCRE and POSIX

ABAP supports POSIX-style regular expressions as of NetWeaver 7.0

SAP 2008 / SAP TechEd 08 / COMP361 Page 14

SAP TechEd 08

Example: Remove HTML Tags

<h2 id="slogan">Leading the Web to Its Full Potential...</h2> <p class="small">The World Wide Web Consortium (<acronym>W3C</acronym>) develops interoperable technologies to lead the Web to its full potential. W3C is a forum for information, commerce, communication, and collective understanding. On this page, you'll find <a href="#news">W3C news</a>, links to <a href="#technologies">W3C technologies</a> and ways to <a href="#contents">get involved</a>. New visitors can find help in <cite><a href="/2002/03/new-to-w3c">Finding Your Way at W3C</a></cite>. We encourage you to read the <cite><a href="/Consortium/Prospectus/">Prospectus </a></cite> and learn <a href="/Consortium/">more about W3C</a>.</p>'

<>

Leading the Web to Its Full Potential... The World Wide Web Consortium (W3C) develops interoperable technologies to lead the Web to its full potential. W3C is a forum for information, commerce, communication, and collective understanding. On this page, you'll find W3C news, links to W3C technologies and ways to get involved. New visitors can find help in Finding Your Way at W3C. We encourage you to read the Prospectus and learn more about W3C.

REPLACE ALL OCCURRENCES OF ?????? IN text WITH ''. '<[^>]*>'


SAP 2008 / SAP TechEd 08 / COMP361 Page 15

Building Regular Expressions

Regular expressions are patterns built from


Literals

(characters) Operators (meta characters) . * + ? | ^ $ \ ( ) [ ] { } Prepending " \ " turns operators into literals

A regular expression pattern


represents a set of text strings matches text if entire text is represented by RE is used for searching text Regex 'hel+o' represents "helo", "hello", "helllo", ... matches "hello" is found in text "hello, world"
SAP 2008 / SAP TechEd 08 / COMP361 Page 16

SAP TechEd 08

Basic Regex Building Blocks

Basic regex building blocks


The

dot " . " matches any single character The bar " | " lists alternatives Parentheses " ( ) " group subexpressions

Examples
RE a.b a|bc|de a|b(c|d) a(b|c.)d a|b|c|d|e|f Matches aab, a1b, a%b, a, bc, de a, bc, bd abd, acxd, ac$d, a, b, c, d, e, f Doesn't Match ab, aabb, acd, abxd, acxxd,

SAP 2008 / SAP TechEd 08 / COMP361 Page 17

Adding Quantifiers to Regular Expressions

Matching multiple characters at once

Asterisk " * " denotes arbitrary repetition of previous character Op. r* r+ r{m,n} r? Represents zero or more repetitions of r one or more repetitions of r between m and n repetitions optional r Example ab* .* ab+ a{2,4} ab?c Matches a, ab, abb, (anything) ab, abb, aa, aaa, aaaa ac, abc

Use " ( ) " to repeat more complex subexpressions (aa|b)* .(..)* (empty), aa, b, aaaa, aab, bb, aaaaaa, (anything with an odd number of characters)

SAP 2008 / SAP TechEd 08 / COMP361 Page 18

SAP TechEd 08

Sets and Classes

Sets define single character alternatives concisely


Literals Ranges Negation Mixed
Operators To

[aA1.] [a-c0-9] [^aA1] [^0-9]

a, A, 1, or . a, b, c, or any digit any one character but a, A, or 1 any one character but a digit

like " * . ( ) " have no special meaning inside sets

include " [ ] ^ - \ ", use escape character " \ " Ranges such as [-] may be platform-dependent

Caution!

Predefined classes provide cross-platform character subsets


Letters [:alpha:] Digits [:digit:] \d \D
SAP 2008 / SAP TechEd 08 / COMP361 Page 19

Alphanum [:word:] \w \W

Lowercase [:lower:] \l \L

Whitespace [:space:] \s \S

Control [:cntrl:]

Validating Data With Regular Expressions

Validating data with regular expressions


Data

input is valid if and only if it matches against regex pat IF cl_abap_matcher=>matches( pattern = pat text = input ) = abap_true. " accept valid input ELSE. " reject invalid input ENDIF.

False

positives = data is invalid but matches False negatives = data is valid but does not match
Strike

the right trade-off: Complexity of regex vs Cost of false positives/negatives

SAP 2008 / SAP TechEd 08 / COMP361 Page 20

10

SAP TechEd 08

Working With Regular Expressions

Design regex that matches given input if input resembles a plausible credit card number
Check

for valid symbols [\d\s\-]+


\d = 1 digit \s = 1 whitespace

Check

for correct number of digits \d{15,16}

Combining

both checks: Naive approach [\d\s\-]{15,16}

Combining

both checks: Correct version \s*(\d[\s\-]*){15,16}

SAP 2008 / SAP TechEd 08 / COMP361 Page 21

Exercise: Write simple regular expressions that


match all text samples shown in the left column and do not match any text samples shown in the right column

System access

Log into system M55 Start transaction SE38 Run report ZTE08_REGEX_EX1

Usage

Click on arrows to navigate between individual exercises Click SHOW to display sample solution

EXERCISE 1a
SAP 2008 / SAP TechEd 08 / COMP361 Page 22

11

SAP TechEd 08

Using Regular Expressions in ABAP

RE support integrated into FIND and REPLACE statements


Finding

first occurrence FIND REGEX pattern IN text MATCH OFFSET off MATCH LENGTH len.

Replacing

all occurrences

REPLACE ALL OCCURRENCES OF REGEX pattern IN text WITH new REPLACEMENT COUNT cnt.
Supports

all known additions, e.g., IGNORING CASE support for FIND ALL OCCURRENCES Additional support for searching internal tables REs limited to CHARACTER MODE
Additional

SAP 2008 / SAP TechEd 08 / COMP361 Page 23

Searching With Regular Expressions

Searching returns leftmost-longest match within text


FIND REGEX '.at' IN text ... The cat with the hat sat on Cathy's mat. cat hat

sat

Cat

mat

"Leftmost" takes precedence over "longest"


FIND REGEX '.at(\w|\s)*th' IN text ... The cat with Cathy's hat thus sat on the mat. cat with cat with Cath hat th hat thus sat on th sat on th
SAP 2008 / SAP TechEd 08 / COMP361 Page 24

12

SAP TechEd 08

Getting Information From FIND and REPLACE

Obtain individual information by using additions


FIND REGEX pattern IN [TABLE] text MATCH COUNT cnt MATCH LINE lin MATCH OFFSET off MATCH LENGTH len.
Contains Success Get

REPLACE REGEX pattern IN [TABLE] text WITH new REPLACEMENT COUNT cnt REPLACEMENT LINE lin REPLACEMENT OFFSET off REPLACEMENT LENGTH len.

information about the last match/replacement, if any

indicated by sy-subrc and MATCH COUNT match text by offset and length access
text+off(len)

Replacement Not

information is about replacement text, not text replaced suitable for obtaining information on all matches/replacements

SAP 2008 / SAP TechEd 08 / COMP361 Page 25

Using ABAP Regex Classes

ABAP Objects provides two classes for using REs


Regex

class cl_abap_regex
cl_abap_regex

Stores preprocessed RE pattern for increased performance Should be reused to avoid costly re-processing Matcher class cl_abap_matcher Central class for interaction with REs Links text to regex object Stores copy of text to process (efficient for strings, costly for fixed-length fields)

a*b

cl_abap_matcher

Tracks matching and replacing within text

___ ___ ___

$0

Using regex classes in ABAP


Create Use

regex and matcher and interact with matcher static class methods of matcher as a shorthand

SAP 2008 / SAP TechEd 08 / COMP361 Page 26

13

SAP TechEd 08

Using Regex Classes for Matching

The matcher objects keeps track of the current match


1. Initially, there is no match 2. By calling find_next( ), the next unprocessed match in text is located and stored in the matcher object

cl_abap_matcher

___ ___ ___

-cl_abap_matcher

___ ___ ___ 5. By calling replace_found( ), the match just found is replaced as specified
SAP 2008 / SAP TechEd 08 / COMP361 Page 27

match

3. Information about the current match can be retrieved by calling get_match( ).

4. By calling find_next( ) again, the matcher advances to the next unprocessed match

Matcher Interface

Finding find_next( ) match( ) Replacing replace_found( new ) replace_next( new ) Querying get_offset( [index] ) get_length( [index] ) get_line( ) get_match( ) get_submatch( index ) replace_all( new ) find_all( )

SAP 2008 / SAP TechEd 08 / COMP361 Page 28

14

SAP TechEd 08

Typical ABAP Code For Using Regex Classes

Set

up matcher using factory

DATA matcher TYPE REF TO cl_abap_matcher. matcher = cl_abap_matcher=>create( pattern = 'a*b' text = mytext ).

Process

text with find and replace

WHILE matcher->find_next( ) = abap_true. * query match found len = matcher->get_length( ). * determine replacement repl = compute_my_replacement( len ). matcher->replace_found( repl ). ENDWHILE.
SAP 2008 / SAP TechEd 08 / COMP361 Page 29

Working With Submatches

Capturing parentheses store submatches for later reference


(\d+)/(\d+)
Match

required by 10/31 at the latest

is subdivided into submatches and stored internally


(\d+) i r e d b y 1 0 / / (\d+) 3 1 a t t h e

1st submatch
One

2nd submatch

of the most useful features of REs!

Submatches can be
retrieved referred

for further analysis/processing to within pattern referred to within replacement


SAP 2008 / SAP TechEd 08 / COMP361 Page 30

15

SAP TechEd 08

Extracting Parts With Submatches

Submatches extract selected parts from a larger text


url = 'http://sap.com/&login=frank@secret&lang=EN'.
Use

regex to locate information in larger text


http://sap.com/&login=frank@secret&lang=EN &login=\w+@\w+

Use

subgroups to extract relevant parts only


&login=frank@secret &login=(\w+)@(\w+)

Submatches

easily retrieved with FIND additions

DATA: user TYPE string, pass TYPE string. FIND REGEX '&login=(\w+)@(\w+)' IN url SUBMATCHES user pass.
SAP 2008 / SAP TechEd 08 / COMP361 Page 31

Avoiding Common RE Pitfalls (1)

Matches are greedy " .* " usually matches way too much
Wrong

approach for matching delimited parts


<.*> try to match HTML tag

This

greedily matches the largest possible substring Some we <want>, and some we <don't>.

Solution:

Include delimiters in negated character set


<[^>]*> inside * loop stops at first > character seen

SAP 2008 / SAP TechEd 08 / COMP361 Page 32

16

SAP TechEd 08

Avoiding Common RE Pitfalls (2)

Part delimiters may be escaped or quoted


Too-relaxed

approach for extracting ABAP string literals

FIND ALL OCCURRENCES OF REGEX '`[^`]*`' RESULTS res.


This

will stop at doubled quotes within character literals WRITE / `The ``good' news is ...`.

Possible

solution: List exceptions explicitly `([^`]|``)*`

Applies

similarly to quoted delimiters: <tag attr="abc>xyz"> <([^>]|"[^"]+")*>

SAP 2008 / SAP TechEd 08 / COMP361 Page 33

Going Overboard

So youd like to reject all invalid dates 2/30/2006 Would you use this regex then? ^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30 |29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2 -9]\d)?(?:0[48]|[2468][048]|[13579][26])| (?:(?:16|[2468][048]|[3579][26])00)))(?:\ x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-./])(?: 1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d( ?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(: [0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3]) (:[0-5]\d){1,2})?$ Some things are best left to ABAP!
SAP 2008 / SAP TechEd 08 / COMP361 Page 34

17

SAP TechEd 08

Summary Efficient Processing of Text

Data types STRING and XSTRING support efficient text processing


Dynamic memory allocation Sharing & Copy-on-Demand

Regular Expressions

Powerful to describe patterns of text Used for validation, searching, extracting of text

To learn more

Run ABAP report DEMO_REGEX_TOY Check the ABAP online documentation

SAP 2008 / SAP TechEd 08 / COMP361 Page 35

Exercise: Write a simple ABAP program that


reads all $ amounts from an input text and replaces them by the doubled value

System access

Log into system M55 Start transaction SE38 Copy report ZTE08_REGEX_EX2_XX

EXERCISE 1b
SAP 2008 / SAP TechEd 08 / COMP361 Page 36

18

SAP TechEd 08

Agenda

1. Efficient Processing of Textual Data


1.1. Recab: String Data Types 1.2. Regular Expressions

2. Extended Expressions 2.1. Enhanced Expression Capabilities


2.2. String Expressions

3. New Features of Internal Tables


3.1. Dynamic WHERE Condition 3.2. Secondary Keys

SAP 2008 / SAP TechEd 08 / COMP361 Page 37

Expressions Situation before NetWeaver 7.10

Computational

expressions only supported in COMPUTE statement

Arithmetic expressions (calculating numbers) Binary expressions (calculating bits)

Only

pure logical expressions used in control statements

tmp1 = n / i. tmp2 = ME->meth( tmp1 ) * i. IF tmp2 = n. EXIT. ENDIF.


Swamping Restricted

of code with helper variables

use of few built-in functions and functional methods in very few operand positions only

SAP 2008 / SAP TechEd 08 / COMP361 Page 38

19

SAP TechEd 08

Expressions Situation as of NetWeaver 7.10

New

kind of computational expression: String expressions Computational expressions supported in


various (input) operand positions logical expressions

IF ME->meth( n / i ) * i EXIT. ENDIF.


Computation as actual method parameter
Enlarged

= n.

Computation as operand in a logical expression

set of built-in functions including string and predicate functions Functional methods allowing nested and chained method calls
Compact

and efficient code with in-place expressions

SAP 2008 / SAP TechEd 08 / COMP361 Page 39

Examples for New Expression Positions


v1 v2 v3 IF = a + b. = c - d. = meth( v2 ). v1 > v3.
In logical expressions

IF a + b > meth( c d ).
Numeric input operand

len = strlen( txt ) - 1. DO len TIMES. idx = lines( itab ). READ TABLE itab INDEX idx regex = oref->get_pat( ). FIND REGEX regex IN txt.

DO strlen( txt ) 1 TIMES. READ TABLE itab INDEX lines( itab ) FIND REGEX oref->get_pat( ) IN txt.
Method call in generic input operands

tab = oref->tab( ). start = i + 1. end = n 1. APPEND LINES OF tab FROM start TO end TO t.
SAP 2008 / SAP TechEd 08 / COMP361 Page 40

APPEND LINES OF oref->tab( ) FROM i + 1 TO n 1 TO t.

20

SAP TechEd 08

Expressions in Method Parameters

o->m( abs( i * 2 ) + 1 ). cl=>m( p1 = i + 1 p2 = 2 ** j ).

Unnamed actual parameter Named actual parameters Parameter is method call

o->m( cl=>m( p1 = o->i~m( 7 ) ) ). cl=>m( pInt = 12 / 10 pDec = 12 / 10 ).

Any numeric formal parameter accepts arithmetic computation Formal parameter type contributes to calculation type (pInt 1, pDec 1.2)

o->m( pX10 = BIT-NOT x1 pXStr = x1 BIT-OR x2 ).

Any binary formal parameter accepts binary computation Instance constructor parameter Exception constructor parameter

CREATE OBJECT o EXPORTING p = i + 1 . RAISE EXCEPTION TYPE lcx EXPORTING p = i + 1 .

SAP 2008 / SAP TechEd 08 / COMP361 Page 41

Method Call Chains

Chained method call

cl=>m1( )->m2( ).
Terminal chained attribute access

IF o->m1( )->intf~m2( )->a > 1.


Intermediate chained attribute access

CASE cl=>m1( )->obj->m2( ) .

SAP 2008 / SAP TechEd 08 / COMP361 Page 42

21

SAP TechEd 08

Extended Expressions Pitfalls

*No compiler optimizations, like

common subexpression elimination loop invariant extraction

programmers responsibility: temporary variables

*ABAP is now also obfuscation enabled


lcl=>cm_ii( 1 + abs( lcl=>factory2( f_in1 = lcl=>factory0( )->m_lif( )->im_lif( )->im_ii( i ) f_in2 = lcl=>cm_ii( 2 ** i ) - 3 )->m_ii( lcl=>factory1( f_in = j + 4 )->m_lif_i( 5 )->im_ii( 6 ) ) ) ). But: Debugger support for complex expressions

Display of method return value Display of intermediate computation results (by reducing the step size)

SAP 2008 / SAP TechEd 08 / COMP361 Page 43

Agenda

1. Efficient Processing of Textual Data


1.1. Recab: String Data Types 1.2. Regular Expressions

2. Extended Expressions
2.1. Enhanced Expression Capabilities

2.2. String Expressions 3. New Features of Internal Tables


3.1. Dynamic WHERE Condition 3.2. Secondary Keys

SAP 2008 / SAP TechEd 08 / COMP361 Page 44

22

SAP TechEd 08

String Expressions

New kind of computational expressions: String Expressions


Concatenations String Templates

txt1 && txt2 |Text{ expression format = }Text|

String Expressions

Used to create formatted or technical text (e.g. xml) conveniently Usable in expression positions just like arithmetic or binary expressions Substitute masses of

WRITE TO and character-like helper variables (for conversions and formatting) CONCATENATE

New Built-In Functions


23 functions returning a string result 8 functions returning a non-string result 4 new predicates on strings

SAP 2008 / SAP TechEd 08 / COMP361 Page 45

In-place Concatenations

Concatenation operator txt1 && txt2


Replaces CONCATENATE statement and many auxiliary variables

DATA txt TYPE string. CONCATENATE txt1 txt2 INTO txt. CONDENSE txt. txt = condense( txt1 && txt2 ).

SAP 2008 / SAP TechEd 08 / COMP361 Page 46

23

SAP TechEd 08

String Templates

String Templates mix literal text with evaluated result of expressions |Text{ expression format = }Text|
Literal Text Embedded Expression Format Options Literal Text

result = |{ txt width align WRITE / result. result = |{ txt width align WRITE / result. result = |{ txt width align WRITE / result.

= 20 = left

pad = pad }<---|.

= 20 = center pad = pad }<---|. = 20 = right

pad = pad }<---|.

txt = OOO and pad = x yield


SAP 2008 / SAP TechEd 08 / COMP361 Page 47

String Templates

String Templates

Evaluation includes conversions, formatting and concatenating Directly supports the use of control characters (like \n for newline) Cannot stretch over multiple lines (use & to concatenate across lines) \n| &

s = |Hello, \n| & |today is { sy-datum date = iso } |now is { sy-uzeit time = iso }|.

Replaces WRITE TO statement and many auxiliary variables

if intval < 0. cvar = '-'. write intval to cvar+1 no-sign left-justified no-grouping. s = cvar. else. s = intval. s = |{ intval }|. endif.

SAP 2008 / SAP TechEd 08 / COMP361 Page 48

24

SAP TechEd 08

Literal Text in String Templates

Literal Text

Consists of all characters between | and { resp. } and | (including spaces) May contain escaped characters or control characters
Escape character \ needed for Character \ Character | Character { Character } Control characters Tab (0x9) Newline (0xA) Return (0xD) \t \n \r \\ \| \{ \}

SAP 2008 / SAP TechEd 08 / COMP361 Page 49

Embedded Expressions in String Templates

Embedded Expressions

Introduced by { and } within string template Mandatorily starts with an expression which result is converted to a string

s = |<line index={ sy-tabix } | & |kind={ o->get_kind( ) }>|.

Optional named parameters can be used to format the resulting string

s = |timestamp={sy-datum date = iso }T| & |{sy-uzeit time = iso }|.


Format options

Line breaks within the embedded expression are insignificant

SAP 2008 / SAP TechEd 08 / COMP361 Page 50

25

SAP TechEd 08

General Formatting Options

For all value types


width align pad case [integer number] {left|right|center} [character] {raw|upper|lower} Overall output width Alignment (left is default) Padding character Character case

SAP 2008 / SAP TechEd 08 / COMP361 Page 51

Formatting Options for Numeric Values

For numeric values


sign {left|leftplus|leftspace| right|rightplus|rightspace} exponent decimals zero number style currency [integer number] [integer number] {yes|no} {raw|user|environment} Constants from CL_ABAP_FORMAT Entries from DB table TCURC Sign discipline (left is default) Exponent Number of decimal places Zero suppression Decimal format (raw is default) Output format for floating point numbers Currency code

SAP 2008 / SAP TechEd 08 / COMP361 Page 52

26

SAP TechEd 08

Formatting Options for Date and Time Values

For date and time


date raw user iso environment raw user iso environment space user iso user (20080906) apply user setting (2008-09-06) apply locale setting 182504 apply user setting 18:25:04 apply locale setting date space time user setting data T time apply user setting Date format (raw is default) Time format (raw is default) Time stamp format

time

timestamp

timezone

Values from DB-table TTZZ-TZONE

Time zone

SAP 2008 / SAP TechEd 08 / COMP361 Page 53

String Processing before Release 7.10

Set of statements, e.g., CONCATENATE SPLIT CONDENSE FIND SUBSTRING | REGEX REPLACE SUBSTRING | REGEX Set of logical operators , e.g., CS, NS CA, NA CP, NP Set of built-in describing functions , e.g., strlen( ... ) charlen( ... ) Substring access via offset-length specification ... text+off(len) ...
SAP 2008 / SAP TechEd 08 / COMP361 Page 54

27

SAP TechEd 08

New Built-in String Functions Examples

String processing is now directly available in expressions result = condense( val = ` Rock'xxx'Roller` del = `re ` from = `x` to = `n` ). gives "Rock'n'Roll" html = `<title>This is <i>title</i></title>`. repl = `title`. html = replace( val regex with occ = = = = html repl && `(?![^<>]*>)` `Treasure Island` 0 ).

gives "<title>This is <i>Treasure Island</i></title>" IF contains( val = email match = `\w+(\.\w+)*@(\w+\.)+(\w{2,4})` ). true if email contains a valid e-mail address
SAP 2008 / SAP TechEd 08 / COMP361 Page 55

Functions Returning a String (1)

Extracting Substrings substring( val = s [off = i1] [len = i2] ) substring_after( val = s (sub|regex) = s1 [occ = i1] [len = i2] ) substring_from( val = s (sub|regex) = s1 [occ = i1] [len = i2] ) substring_before( val = s (sub|regex) = s1 [occ = i1] [len = i2] ) substring_to( val = s (sub|regex) = s1 [occ = i1] [len = i2] ) segment( val = s index = i [sep = s1] ) match( val = text regex = regex [occ = occ] ) Shifting Strings shift_left( [val =] s [places = i1 | circular = i2 | sub = s1] ) shift_right( [val =] s [places = i1 | circular = i2 | sub = s1] )
SAP 2008 / SAP TechEd 08 / COMP361 Page 56

28

SAP TechEd 08

Functions Returning a String (2)

Transforming Strings replace( val = s (sub|regex) = s1 with = s2 [occ = i1] [case = c] ) insert( val = s sub = s1 [off = i] ) repeat( val = s occ = i ) condense( [val =] s [del = s1] [from = s2] [to = c] ) reverse( [val =] s ) escape( val = s format = f ) translate( val = s from = s1 to = s2 ) to_upper([val =] s ) to_lower([val =] s ) to_mixed( [val =] s [sep = c1] [case = c2] [min = i] ) from_mixed( [val =] s [sep = c1] [case = c2] [min = i] )

SAP 2008 / SAP TechEd 08 / COMP361 Page 57

Functions Returning a String (3)

Concatenation of table lines concat_lines_of( [table =] t [sep = s] ) Boolean Evaluations boolc( logical-expression ) boolx( bit = i bool = logical-expression ) Returns X if logical-expression is true else Returns byte with bit i set to 1 if logicalexpression is true else 0 (bit-set) Concatenates lines of <t> separated by <s>

if condition . temp_flag = 'X'. else. temp_flag = ' '. endif. oref->meth( temp_flag ).

oref->meth( boolc( condition ) ).

SAP 2008 / SAP TechEd 08 / COMP361 Page 58

29

SAP TechEd 08

Functions Describing Strings

Searching Substrings (Return the offset of the found location) find( val = s (sub|regex) = s1 [off = i1] [len = i2] [occ = i3] [case = c] ) find_end( val = s (sub|regex) = s1 [off = i1] [len = i2] [occ = i3] [case = c] ) find_any_of( val = s sub = s1 [off = i1] [len = i2] [occ = i3] ) find_any_not_of( val = s sub = s1 [off = i1] [len = i2] [occ = i3] ) Counting Substrings (Return number of found locations) count( val = s (sub|regex) = s1 [off = i1] [len = i2] [occ = i3] [case = c] ) count_any_of( val = s sub = s1 [off = i1] [len = i2] [occ = i3] ) count_any_not_of( val = s sub = s1 [off = i1] [len = i2] [occ = i3] ) Similarity of Strings (Returns Levenshtein distance) distance( val1 = s1 val2 = s2 [max = i] )
SAP 2008 / SAP TechEd 08 / COMP361 Page 59

Predicate Functions on Strings

Containing Substrings or Characters contains( val = s (sub|start|end|regex) = s1 [off = i1] [len = i2] [occ = i3] [case = c] ) contains_any_of( val = s (sub|start|end) = s1 [off = i1] [len = i2] [occ = i3]) contains_any_not_of( val = s (sub|start|end) = s1 [off = i1] [len = i2] [occ = i3] ) Matching a Regular Expression matches( val = text regex = regex [off = off] [len = len] )

SAP 2008 / SAP TechEd 08 / COMP361 Page 60

30

SAP TechEd 08

Summary Extended Expressions

Extended use of expressions


Supported in many operand positions, especially for internal table statements Seamless integrated in OO context (nested method calls, chaining)

String expressions

Simple, however very powerful Intuitively use like arithmetic expressions Rich set of formatting options Rich set of built-in string functions

To learn more

Run ABAP report DEMO_EXPRESSIONS Check the ABAP online documentation

SAP 2008 / SAP TechEd 08 / COMP361 Page 61

Exercise: Write a simple ABAP program that

creates an HTML page using string templates

System access

Log into system M55 Start transaction SE38 Copy report ZTE08_STRING_EX_XX

EXERCISE 2
SAP 2008 / SAP TechEd 08 / COMP361 Page 62

31

SAP TechEd 08

Agenda

1. Efficient Processing of Textual Data


1.1. Recab: String Data Types 1.2. Regular Expressions

2. Extended Expressions
2.1. Enhanced Expression Capabilities 2.2. String Expressions

3. New Features of Internal Tables


3.1. Dynamic WHERE Condition 3.2. Secondary Keys

SAP 2008 / SAP TechEd 08 / COMP361 Page 63

Need for a dynamic WHERE condition

The ABAP environment gives programmers powerful meta programming facilities for generic programming

Dynamic or generic language support Introspection abilities (RTTC) Program generation (at runtime)

Problem:

Some constructs of ABAP can only be used statically. Therefore programmers are often forced to use program generation as a work around

SAP 2008 / SAP TechEd 08 / COMP361 Page 64

32

SAP TechEd 08

Dynamic WHERE Condition since 7.10

One of these missing features is now available:

LOOP with dynamic WHERE condition

generic

generic

dynamic

SAP 2008 / SAP TechEd 08 / COMP361 Page 65

Features

The dynamic WHERE condition obeys the same rules as the static WHERE condition:

For the left hand side of the operators are only components of the table line permitted The right hand side is evaluated at the LOOP entry.

Dynamic WHERE conditions can also be specified for:


MODIFY ... WHERE DELETE ... WHERE

(The same rules apply in these cases.)

SAP 2008 / SAP TechEd 08 / COMP361 Page 66

33

SAP TechEd 08

Elements of a dynamic WHERE condition

Examples for allowed constructs are:


All arithmetic and string operations

Boolean operator: and, or, not, equiv

SAP 2008 / SAP TechEd 08 / COMP361 Page 67

Additional Features

Dynamic WHERE conditions can also handle the following constructs


Method calls and attribute access Arithmetic expressions Predefined functions Access via data references Dynamic WHERE condition has full secondary key support

Performance aspects

The component and value parts should have the same type to avoid internal conversions. If a table key is appropriately covered (left initial piece for SORTED, all components for HASHED keys) the WHERE condition can be optimized As an internal optimization a cache is implemented to reuse static information

SAP 2008 / SAP TechEd 08 / COMP361 Page 68

34

SAP TechEd 08

Exception handling

There is the exception CX_SY_ITAB_DYN_LOOP to handle incorrect WHERE conditions

SAP 2008 / SAP TechEd 08 / COMP361 Page 69

DEMO
SAP 2008 / SAP TechEd 08 / COMP361 Page 70

35

SAP TechEd 08

Agenda

1. Efficient Processing of Textual Data


1.1. Recab: String Data Types 1.2. Regular Expressions

2. Extended Expressions
2.1. Enhanced Expression Capabilities 2.2. String Expressions

3. New Features of Internal Tables


3.1. Dynamic WHERE Condition 3.2. Secondary Keys

SAP 2008 / SAP TechEd 08 / COMP361 Page 71

Why Secondary Keys for Internal Tables ?

Benefits from key tables (available since 4.0)


Fast

O(1) key access for hashed tables

time

size
O(1)

SAP 2008 / SAP TechEd 08 / COMP361 Page 72

36

SAP TechEd 08

Why Secondary Keys for Internal Tables ?

Benefits from key tables (available since 4.0)


Fast

O(1) key access for hashed tables Fast O(log n) key access for sorted tables Fast partial sequential processing for sorted tables (LOOP WHERE optimization)

time

size
O(log n) O(1)

SAP 2008 / SAP TechEd 08 / COMP361 Page 73

Why Secondary Keys for Internal Tables ?

Benefits from key tables (available since 4.0)


Fast

O(1) key access for hashed tables Fast O(log n) key access for sorted tables Fast partial sequential processing for sorted tables (LOOP WHERE optimization)

Low performance in productive context

Non-primary key access


Slow

time

O(n) runtime behavior cause performance problems To be optimized by error prone hand-coded secondary key access
Might

Good perfomance at first glance

size
O(n) O(log n) O(1)

SAP 2008 / SAP TechEd 08 / COMP361 Page 74

37

SAP TechEd 08

Evolution of Internal Tables

Standard Tables
Since the beginning of ABAP in the 80ies

Sorted/Hashed Tables
Since mid of the 90ies

Secondary Keys
Coming with NetWeaver 7.1

Counterpart to database tables Paged memory allocation (high scalability) Fast index access Linear key access (O(n))

Fast key access (O(log n)) for sorted tables O(1) for hash tables High scalability due to Tree data structures for the indices of sorted tables

Additional (multiple) secondary keys on arbitrary internal tables Lazy index update Saves memory costs Reduces runtime costs Delayed index update for unique keys

General purpose hash administration for hash tables

SAP 2008 / SAP TechEd 08 / COMP361 Page 75

Secondary Keys Design Goals

Provide secondary key support analogously to database


Multiple

secondary keys are allowed key definitions are warned

Contradictory

Ease of use
Canonical Only

embedding into the ABAP language

moderate changes necessary to make use of secondary keys in existing programs

No change of semantics when adding secondary keys to a table type definition (compatibility)
No

automatism in selecting an appropriate key at statement level specification of the key to be used, instead

Explicit Syntax

warning if some secondary key seems to fit better (workflow support for code refactoring projects)

SAP 2008 / SAP TechEd 08 / COMP361 Page 76

38

SAP TechEd 08

Defining Secondary Keys

Secondary However,

keys are part of a table type definition, i.e. they are statically defined

the key and its components to be used in a statement (READ, LOOP, ) can be specified dynamically definition of a secondary key has to be complete, i.e. the following properties have to be fully specified Name of the key: it has to be unique for the table Access kind: HASHED or SORTED Uniqueness kind: UNIQUE or NON-UNIQUE, where a hash key has to be unique Key components: either a user-defined list of component names or the pseudo-component TABLE_LINE

The

Reserved Up

key names: PRIMARY_KEY and LOOP_KEY

to 15 secondary keys

SAP 2008 / SAP TechEd 08 / COMP361 Page 77

Non-Unique vs. Unique Secondary Keys

Non-unique (sorted) secondary keys


Lazy

index update, i.e. index is not flushed before it is actually used

No memory costs if not used Thus, perfectly suitable to tune existing programs

Unique secondary keys


Uniqueness

is a semantic constraint, i.e. immediate response (exception/runtime error) if violated by atomic operations (INSERT, MOVE, SELECT, )

SAP 2008 / SAP TechEd 08 / COMP361 Page 78

39

SAP TechEd 08

Defining Secondary Keys - Examples

SAP 2008 / SAP TechEd 08 / COMP361 Page 79

Defining Secondary Keys Redundancy Warnings


Syntax check warns if redundant key definitions are found

SAP 2008 / SAP TechEd 08 / COMP361 Page 80

40

SAP TechEd 08

Defining Secondary Keys ABAP Dictionary


ABAP Dictionary (SE11) New tabstrip Secondary Key Up to 15 secondary table keys allowed

SAP 2008 / SAP TechEd 08 / COMP361 Page 81

DEMO
SAP 2008 / SAP TechEd 08 / COMP361 Page 82

41

SAP TechEd 08

Database table vs. Internal table: Comparison of secondary keys


Database tables:

Optimizer decides which key to be taken In general, the result set is returned in an arbitrary order, i.e. SELECT has set semantics

Internal tables:

Order of entries in a table is well


STANDARD/HASHED tables: insert order

SORTED tables: insert position (duplicates inserted on top of already existing entries with the same key values) No implicit decision of the key to be taken possible Therefore, explicit key specification required

SAP 2008 / SAP TechEd 08 / COMP361 Page 83

Why is there no Implicit Optimization?

x 2 1 3

y 1 3 2

Name Miller Johnson Smith

Results using primary key


Miller Smith Johnson
different order

Results using secondary key


Johnson Miller Smith

SAP 2008 / SAP TechEd 08 / COMP361 Page 84

42

SAP TechEd 08

Using Secondary Keys: INSERT, MOVE, SELECT, ...


INSERT into a table with secondary keys:

There are no syntax extensions for secondary keys for the inserting statements (INSERT, MOVE, SELECT INTO, ) The primary key is updated immediately NOOP for a single INSERT on a SORTED or HASHED tables, if the entry already exists (return code instead) Runtime error in case of block operations for DupRecs Unique secondary keys are also immediately updated Catchable exception for a single INSERT operation Runtime error in case of block operations for DupRecs

Non-unique secondary keys have a lazy update They are updated when the table is accessed using this key No memory costs before first use (except basic administrative costs)

SAP 2008 / SAP TechEd 08 / COMP361 Page 85

Using Secondary Keys: READ with Respect to a Secondary Key


New addition USING KEY KeyName

New addition KeyName COMPONENTS for WITH clauses

SAP 2008 / SAP TechEd 08 / COMP361 Page 86

43

SAP TechEd 08

Using Secondary Keys: LOOP with Respect to a Secondary Key


New addition USING KEY KeyName

Same rules as for READ in combination with a WHERE-clause


Condition

to be given in the following form:

comp1 = val1 AND AND compn = valn


Additional

non-key components may follow connected with AND

SAP 2008 / SAP TechEd 08 / COMP361 Page 87

Using Secondary Keys: Other Statements Supporting Secondary Keys


Addition USING KEY KeyName for DELETE and MODIFY

SAP 2008 / SAP TechEd 08 / COMP361 Page 88

44

SAP TechEd 08

Using Secondary Keys: Key Components have to be provided


Using a secondary key in combination with WHERE ... or WITH KEY ... requires the following:

for a HASHED key all components have to be listed for a SORTED key at least a left initial part of the key component list has to be given

This is a difference between the (implicitly used) primary table key and secondary keys. The reason is that the expected runtime optimizations can only be achieved under these conditions.

SAP 2008 / SAP TechEd 08 / COMP361 Page 89

Tool Support: Performance Hints by the ABAP Compiler (1)


If specified, a secondary keys must be usable:

Syntax error if it can be statically decided that a key cannot be used Runtime error if this occurs in dynamically specified statements

SAP 2008 / SAP TechEd 08 / COMP361 Page 90

45

SAP TechEd 08

Tool Support: Performance Hints by the ABAP Compiler (2)


If no specific key is given, the compiler checks

Whether some secondary can be used efficiently for the particular statement and gives syntax warnings These warnings are switchable by pragmas (available with 7.11)

SAP 2008 / SAP TechEd 08 / COMP361 Page 91

Tool Support: Debugging Support for Secondary Keys


Special features of the new ABAP debugger for secondary keys:

Flush for outdated non-unique secondary Watch points on secondary key changes Debugger symbol key_status( ItabName KeyName )

Other helpful debugger features:

Memory objects (hit lists) Identify how much memory is currently occupied by an internal table Memory snap shots Make snap shots before and after flushing a secondary key to get the memory actually allocated by the flush

SAP 2008 / SAP TechEd 08 / COMP361 Page 92

46

SAP TechEd 08

Tool Support: Flushing Non-Unique Keys in Debugger

Data of the non-unique key NUSORT is outdated Use to flush it

SAP 2008 / SAP TechEd 08 / COMP361 Page 93

Tool Support: Watch points on Key changes


Debugger symbol key_status( ItabName KeyName)

Returns 1, if the secondary key keyName is outdated Returns 0, if it is up-to-date

Can be used in a watchpoint definition

SAP 2008 / SAP TechEd 08 / COMP361 Page 94

47

SAP TechEd 08

DEMO
SAP 2008 / SAP TechEd 08 / COMP361 Page 95

Incremental Key Changes

Delayed index update for incremental key changes


No index flush if key components are changed via pointer or reference access Update is delayed until the next table statement or the table is passed as a parameter to a method, function, Avoids duplicate record exception during update for unique keys Requires debugging support (watch points on key changes) because there might be a significant time gap between the key changes and the index flush

SAP 2008 / SAP TechEd 08 / COMP361 Page 96

48

SAP TechEd 08

Delayed Update of Unique Keys

Unique key

16 17

5 5

SAP 2008 / SAP TechEd 08 / COMP361 Page 97

Delayed Update of Unique Keys

Unique key

16 17

5 5

ref

SAP 2008 / SAP TechEd 08 / COMP361 Page 98

49

SAP TechEd 08

Delayed Update of Unique Keys

Unique key

17 17

5 5

ref

Immediate update would result in a duplicate record exception ! Therefore, update is delayed until next table statement
SAP 2008 / SAP TechEd 08 / COMP361 Page 99

Delayed Update of Unique Keys

Unique key

17 17

4 5

ref

SAP 2008 / SAP TechEd 08 / COMP361 Page 100

50

SAP TechEd 08

Delayed Update of Unique Keys

Unique key

17 17

4 5

ref

SAP 2008 / SAP TechEd 08 / COMP361 Page 101

Active Key Protection

Primary key components are write protected

Key components of sorted or hash tables are write protected, i.e. no changes via pointers or references possible (runtime error)

Generalization for secondary keys

Within a loop with respect to a certain secondary key, the corresponding key components are also write protected Within nested loops, the union of the primary key components and all secondary key components currently in use (active keys) are write protected

Technically this requires key component surveillance at every write operation

Components of non-active keys can be overwritten (delayed index update)

Otherwise, i.e. if all components of all secondary keys would also be write protected: adding additional keys to an already existing internal table might result in incompatibility

SAP 2008 / SAP TechEd 08 / COMP361 Page 102

51

SAP TechEd 08

Active Key Violation - Example

The following coding shows an example for an active key violation resulting in the runtime error ITAB_ACTIVE_KEY_VIOLATION

SAP 2008 / SAP TechEd 08 / COMP361 Page 103

Summary: Features

The design of secondary keys allows an easy integration in existing and new coding

Few syntax additions (USING KEY, COMPONENTS) to define and use secondary keys Syntax check support by redundancy warnings and performance hints Performance of existing programs can easily be improved by supplementing secondary keys (compatibility) Powerful delta management by lazy and delayed update handling

SAP 2008 / SAP TechEd 08 / COMP361 Page 104

52

SAP TechEd 08

Summary: Usage Scenarios

Optimal usage scenario for secondary keys


Very large tables No or only few modifications after initial built-up phase Administrative overhead mainly concentrated on the build-up phase Performance gain for a read access using a "good" secondary key will easily outweigh this

Special usage scenario for unique secondary keys


If data integrity (uniqueness) is important Applies also for small tables

Secondary keys should not be used


For small tables (less than 50 lines) because of administrative and memory overhead If modifications dominate the table processing

SAP 2008 / SAP TechEd 08 / COMP361 Page 105

EXERCISE 3
SAP 2008 / SAP TechEd 08 / COMP361 Page 106

53

SAP TechEd 08

Summary

Topics covered in this workshop


We introduced techniques for

Processing text-based information using strings, regular expressions and string functions Writing compact code using new expressions capabilities Creating well-formatted or technical text using string templates Generic programming using dynamic WHERE conditions Efficiently managing large amounts of data stored in internal tables using secondary keys

SAP 2008 / SAP TechEd 08 / COMP361 Page 107

Appendix
SAP 2008 / SAP TechEd 08 / COMP361 Page 108

54

SAP TechEd 08

ABAP Debugger Memory Objects

Check memory consumption with the Memory Analysis Tool:


Press button Special Tools Memory Analysis Bound memory: memory that will be available again for the current user session after freeing the table Referenced memory: includes also memory reachable via references

SAP 2008 / SAP TechEd 08 / COMP361 Page 109

ABAP Debugger Memory Snap Shots

Make/compare memory snap shots using the Memory Analysis Tool:


Press button Special Tools Memory Analysis Press button to invoke the Memory Analysis Services dialog Make snap shots before and after flushing; invoke Memory Inspector Compare them by pressing the compare button

SAP 2008 / SAP TechEd 08 / COMP361 Page 110

55

SAP TechEd 08

Memory Costs for Secondary Keys


Memory costs (32/64 bit architectures):

Basic admin costs


If the table has secondary keys at all If it has at least one non-unique secondary key (row id per line)

~ 32/48 bytes 8 bytes / line

Costs per secondary key


Basic admin costs Sorted keys Hashed keys

~ 28/36 bytes 4 - 6 bytes / line ~ 18 bytes / line

Costs for lazy update


Additional index needed after DELETE/SORT Costs for delayed update Heavily depending on the number of changes

4 - 6 bytes / line

Performance improvements to be paid by increased memory consumption

SAP 2008 / SAP TechEd 08 / COMP361 Page 111

Maintenance Costs for Secondary Keys

Maintenance costs for the indices of secondary keys:

Non-unique keys

No costs at all before first flush (lazy update) No costs if already up-to-date Costs for inserting entries that have been inserted since last flush

Unique keys Immediate update costs at every insert operation Update costs caused by delayed (incremental) key changes

Total key maintenance :

Sum of the costs for every table key

Avoid unnecessary key definitions

SAP 2008 / SAP TechEd 08 / COMP361 Page 112

56

SAP TechEd 08

Traps and Pitfalls

Avoid DELETE using secondary key on a STANDARD table:


Locating the entry to be deleted with respect to some secondary key is fast However, all other keys have to be updated, too In particular, the corresponding entry in the primary key has to be search linearly Thus, overall runtime behavior is linear

Avoid modifying unique secondary keys in the Debugger:

Due to the delayed update feature, this may lead to a DupRec error when the next table statement is exceuted

SAP 2008 / SAP TechEd 08 / COMP361 Page 113

Type Check and Table Sharing

Secondary keys are type constitutive, generalizing the type concept in the following ways:

If a table is generic in its primary type, it will also be generic with respect to secondary keys If a table is complete it its primary type, it will also be complete with respect to secondary keys One can force a table to be generic with respect to secondary keys by adding WITH FURTHER SECONDARY KEYS One can force a table to be complete with respect to secondary keys by adding WITHOUT FURTHER SECONDARY KEYS

Two tables are shareable, if the following conditions are satisfied:


Their primary types are shareable They have the same secondary keys

SAP 2008 / SAP TechEd 08 / COMP361 Page 114

57

SAP TechEd 08

Building Your Business with SDN Subscriptions


SDN Subscriptions offers developers and consultants like you, an annual license to the complete SAP NetWeaver platform software, related services, and educational content, to keep you at the top of your profession.
SDN Software Subscriptions: (currently available in U.S. and Germany)
A

one year low cost, development, test, and commercialization license to the complete SAP NetWeaver software platform Automatic notification for patches and updates Continuous learning presentations and demos to build expertise in each of the SAP NetWeaver platform components A personal SAP namespace

SAP NetWeaver Content Subscription: (available globally)


An

online library of continuous learning content to help build skills.

Starter Kit

To learn more or to get your own SDN Subscription, visit us at the Community Clubhouse or at www.sdn.sap.com/irj/sdn/subscriptions
SAP 2008 / SAP TechEd 08 / COMP361 Page 115

Fuel your Career with SAP Certification

What the industry is saying

Teams with certified architects and developers deliver projects on specification, on time, and on budget more often than other teams.
2008 IDC Certification Analysis

82% of hiring managers use certification as a hiring criteria.


2008 SAP Client Survey

SAP Certified Application Professional status is proof of quality, and thats what matters most to customers.*
Conny Dahlgren, SAP Certified Professional

Take advantage of the enhanced, expanded and multi tier certifications from SAP today!
SAP 2008 / SAP TechEd 08 / COMP361 Page 116

58

SAP TechEd 08

Further Information

SAP Public Web: SAP Developer Network (SDN): www.sdn.sap.com Business Process Expert (BPX) Community: www.bpx.sap.com Related SAP Education and Certification Opportunities http://www.sap.com/education/ Related Workshops/Lectures at SAP TechEd 2008
COMP209, News in ABAP Development, Lecture COMP267, ABAP Troubleshooting, Workshop COMP106, ABAP Performance and Trace Analysis, Lecture COMP269, Efficient Database Programming, Lecture COMP272, Memory Efficient ABAP Programming, Workshop COMP273, Test-Driven and Bulletproof ABAP Development, Workshop COMP274, Developing User Interfaces With Web Dynpro for ABAP, Workshop COMP275, State-of-the-Art ABAP -- Programming with ABAP Objects, Workshop COMP277, ABAP Development: Update Your Skills to SAP NetWeaver 7.0, Workshop

SAP 2008 / SAP TechEd 08 / COMP361 Page 117

Thank you!

SAP 2008 / SAP TechEd 08 / COMP361 Page 118

59

SAP TechEd 08

Feedback Please complete your session evaluation.


Be courteous deposit your trash, and do not take the handouts for the following session.

Thank You !
SAP 2008 / SAP TechEd 08 / COMP361 Page 119

Copyright 2008 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. Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. SAP, R/3, xApps, xApp, SAP NetWeaver, Duet, SAP Business ByDesign, ByDesign, PartnerEdge 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 and associated logos displayed are the trademarks of their respective companies. Data contained in this document serves informational purposes only. National product specifications may vary. The information in this document is proprietary to SAP. No part of this document may be reproduced, copied, or transmitted in any form or for any purpose without the express prior written permission of SAP AG. This document is a preliminary version and not subject to your license agreement or any other agreement with SAP. This document contains only intended strategies, developments, and functionalities of the SAP product and is not intended to be binding upon SAP to any particular course of business, product strategy, and/or development. Please note that this document is subject to change and may be changed by SAP at any time without notice. SAP assumes no responsibility for errors or omissions in this document. SAP does not warrant the accuracy or completeness of the information, text, graphics, links, or other items contained within this material. This document is provided without a warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability, fitness for a particular purpose, or non-infringement. SAP shall have no liability for damages of any kind including without limitation direct, special, indirect, or consequential damages that may result from the use of these materials. This limitation shall not apply in cases of intent or gross negligence. The statutory liability for personal injury and defective products is not affected. SAP has no control over the information that you may access through the use of hot links contained in these materials and does not endorse your use of third-party Web pages nor provide any warranty whatsoever relating to third-party Web pages.

Weitergabe und Vervielfltigung dieser Publikation oder von Teilen daraus sind, zu welchem Zweck und in welcher Form auch immer, ohne die ausdrckliche schriftliche Genehmigung durch SAP AG nicht gestattet. In dieser Publikation enthaltene Informationen knnen ohne vorherige Ankndigung gendert werden. Einige von der SAP AG und deren Vertriebspartnern vertriebene Softwareprodukte knnen Softwarekomponenten umfassen, die Eigentum anderer Softwarehersteller sind. SAP, R/3, xApps, xApp, SAP NetWeaver, Duet, SAP Business ByDesign, ByDesign, PartnerEdge und andere in diesem Dokument erwhnte SAP-Produkte und Services sowie die dazugehrigen Logos sind Marken oder eingetragene Marken der SAP AG in Deutschland und in mehreren anderen Lndern weltweit. Alle anderen in diesem Dokument erwhnten Namen von Produkten und Services sowie die damit verbundenen Firmenlogos sind Marken der jeweiligen Unternehmen. Die Angaben im Text sind unverbindlich und dienen lediglich zu Informationszwecken. Produkte knnen lnderspezifische Unterschiede aufweisen. Die in dieser Publikation enthaltene Information ist Eigentum der SAP. Weitergabe und Vervielfltigung dieser Publikation oder von Teilen daraus sind, zu welchem Zweck und in welcher Form auch immer, nur mit ausdrcklicher schriftlicher Genehmigung durch SAP AG gestattet. Bei dieser Publikation handelt es sich um eine vorlufige Version, die nicht Ihrem gltigen Lizenzvertrag oder anderen Vereinbarungen mit SAP unterliegt. Diese Publikation enthlt nur vorgesehene Strategien, Entwicklungen und Funktionen des SAP-Produkts. SAP entsteht aus dieser Publikation keine Verpflichtung zu einer bestimmten Geschfts- oder Produktstrategie und/oder bestimmten Entwicklungen. Diese Publikation kann von SAP jederzeit ohne vorherige Ankndigung gendert werden. SAP bernimmt keine Haftung fr Fehler oder Auslassungen in dieser Publikation. Des Weiteren bernimmt SAP keine Garantie fr die Exaktheit oder Vollstndigkeit der Informationen, Texte, Grafiken, Links und sonstigen in dieser Publikation enthaltenen Elementen. Diese Publikation wird ohne jegliche Gewhr, weder ausdrcklich noch stillschweigend, bereitgestellt. Dies gilt u. a., aber nicht ausschlielich, hinsichtlich der Gewhrleistung der Marktgngigkeit und der Eignung fr einen bestimmten Zweck sowie fr die Gewhrleistung der Nichtverletzung geltenden Rechts. SAP haftet nicht fr entstandene Schden. Dies gilt u. a. und uneingeschrnkt fr konkrete, besondere und mittelbare Schden oder Folgeschden, die aus der Nutzung dieser Materialien entstehen knnen. Diese Einschrnkung gilt nicht bei Vorsatz oder grober Fahrlssigkeit. Die gesetzliche Haftung bei Personenschden oder Produkthaftung bleibt unberhrt. Die Informationen, auf die Sie mglicherweise ber die in diesem Material enthaltenen Hotlinks zugreifen, unterliegen nicht dem Einfluss von SAP, und SAP untersttzt nicht die Nutzung von Internetseiten Dritter durch Sie und gibt keinerlei Gewhrleistungen oder Zusagen ber Internetseiten Dritter ab. Alle Rechte vorbehalten.
SAP 2008 / SAP TechEd 08 / COMP361 Page 120

60