ABAP Programming Comp361

60
SAP TechEd 08 1 COMP361 Advanced ABAP Programming Frank Bertelsmeier, NW F ABAP Daniel Housmans, NW Technical Consulting Sigrid Wortmann, NW F ABAP © SAP 2008 / SAP TechEd 08 / COMP361 Page 2 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.

description

ex

Transcript of ABAP Programming Comp361

Page 1: ABAP Programming Comp361

SAP TechEd 08

1

COMP361Advanced ABAP Programming

Frank Bertelsmeier, NW F ABAPDaniel Housmans, NW Technical ConsultingSigrid Wortmann, NW F ABAP

© SAP 2008 / SAP TechEd 08 / COMP361 Page 2

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.

Page 2: ABAP Programming Comp361

SAP TechEd 08

2

© SAP 2008 / SAP TechEd 08 / COMP361 Page 3

Learning Objectives

As a result of this workshop, you will be able to:Deploy strings for efficient handling of text-based informationMake use of regular expressions to process strings effectivelyWrite compact code by using extended expression capabilitiesUtilize string templates to create formatted textWork proficiently and efficiently with the new features for internal tables

Implement generic services by using dynamic WHERE conditionsOptimize 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 4

1. Efficient Processing of Textual Data1.1. Recab: String Data Types1.2. Regular Expressions

2. Extended Expressions2.1. Enhanced Expression Capabilities2.2. String Expressions

3. New Features of Internal Tables3.1. Dynamic WHERE Condition3.2. Secondary Keys

Agenda

Page 3: ABAP Programming Comp361

SAP TechEd 08

3

© SAP 2008 / SAP TechEd 08 / COMP361 Page 5

Sequential Data Types in ABAP

Business information = sequences of characters or bytesCustomer names, addressesProduct numbers, dates, currenciesXML dataNatural language

Overview of data types in ABAP representing character and byte sequences

D, T, N

Special

STRING

C

Character

XSTRINGVariable Size

XFixed Size

Byte

© SAP 2008 / SAP TechEd 08 / COMP361 Page 6

Comparison of Strings and Fixed-Sized Fields

Some benefits that ABAP strings provideEfficient management of string storage spaceAutomatic garbage collectionAutomatic value sharing with copy-on-write

Max length of 262.143 charsMax length of 2,000,000,000 bytes

Straight quote literals 'fieldlit'Backquote literals `stringlit`

Subfield idiom +offset(length) for read and write access

Substring idiom +offset(length)for read access only

Length fixed and preallocatedLength adjusted dynamically at runtime

Trailing blanks are ignoredTrailing blanks are significant

FieldsStrings

Page 4: ABAP Programming Comp361

SAP TechEd 08

4

© SAP 2008 / SAP TechEd 08 / COMP361 Page 7

String values are stored separately from variables in memory

Decoupling of value and reference allowsEfficient resizing of stringsSharing of string values

Strings Values

DATA: BEGIN OF struc1,a(3) TYPE n,b(10) TYPE c,c(3) TYPE n,

END OF struc1.

DATA: BEGIN OF struc2,a(3) TYPE n,b TYPE string,c(3) TYPE n,

END OF struc2.

1 2 3 A B C D E F 4 5 6H I JG 1 2 3 string reference 4 5 6

A B C D E F G H I J

struc2 is deepstruc1 is flat

string value

a b c a b c

© SAP 2008 / SAP TechEd 08 / COMP361 Page 8

String Storage Allocation

Memory allocation during a typical program run

string reference (8 bytes)DATA str TYPE string.

str = 'first'.

str = 'second value'.

SHIFT str BY 5 PLACES.

str = 'another try'.

str = 'a final value!'.

tsrif

un d v a l eoces

nif la lav !eua

string header (16-32 bytes)

string value (variable)

l u eavd yh e r t rtona

main memory

Page 5: ABAP Programming Comp361

SAP TechEd 08

5

© SAP 2008 / SAP TechEd 08 / COMP361 Page 9

String Sharing

Values may be shared by multiple string references

Unsharing copy-on-write / lazy copyDelays costly copying as long as possible

references + headersDATA: str1 TYPE string,str2 TYPE string,str3 TYPE string.

str1 = 'common'.

str2 = str1.

str3 = str2.

SHIFT str2 BY 4 PLACES.

o nmmoc

no

str1

str2str3

© SAP 2008 / SAP TechEd 08 / COMP361 Page 10

Restrictions on Substrings

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

Use REPLACE statement (or replace function) instead

Field symbols cannot be used for substring accessValue 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. " shifts char positions

DATA str TYPE string VALUE `strvalue`.

WRITE / str+3(4). " OKstr+3(4) = `x`. " would modify value

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

Page 6: ABAP Programming Comp361

SAP TechEd 08

6

© SAP 2008 / SAP TechEd 08 / COMP361 Page 11

Advantages of character fieldsEasy to access (+off(len), flat structures)No internal overhead for accessing value

Advantages of stringsStorage allocated dynamically

Common values are shared

Trailing blanks are significant (may increase performance)

Which Data Type to Choose

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

DATA c80 TYPE c LENGTH 80 VALUE 'hello'.CONCATENATE c80 'world' INTO c80.

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

Checks 75 trailing blanks for finding

end of text

© SAP 2008 / SAP TechEd 08 / COMP361 Page 12

1. Efficient Processing of Textual Data1.1. Recab: String Data Types1.2. Regular Expressions

2. Extended Expressions2.1. Enhanced Expression Capabilities2.2. String Expressions

3. New Features of Internal Tables3.1. Dynamic WHERE Condition3.2. Secondary Keys

Agenda

Page 7: ABAP Programming Comp361

SAP TechEd 08

7

© SAP 2008 / SAP TechEd 08 / COMP361 Page 13

Ubiquitous Text Processing

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

Extracting information from text:What is the document ID requested by the web client?

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

1234 5678 1234 5678 1234 5678 1234 5AB8

1234-5678-1234-5678

+49 (6227) 7-47474 496227747474

http://sap.com/&user=frank&id=1234&lang=EN

© SAP 2008 / SAP TechEd 08 / COMP361 Page 14

Improving Text Processing With REs

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

Well understoodDeveloped by mathematician Kleene in the 1950s

PowerfulHighly focused special purpose languageMany common text processing tasks turn intosimple one-liners

Standardized and widely usedMade popular by Unix tools: grep, sed, awk, emacsBuilt into some languages like Perl and Java;add-on libraries available for many othersEarly Unix de-facto standard formalized in PCRE and POSIX

ABAP supports POSIX-style regular expressions as of NetWeaver 7.0

Stephen C. KleeneImage © U. of Wisconsin

Page 8: ABAP Programming Comp361

SAP TechEd 08

8

© SAP 2008 / SAP TechEd 08 / COMP361 Page 15

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... TheWorld 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 Prospectusand learn more about W3C.

< >

REPLACE ALL OCCURRENCES OF ??????IN text WITH ''.

'<[^>]*>'

© SAP 2008 / SAP TechEd 08 / COMP361 Page 16

Building Regular Expressions

Regular expressions are patterns built fromLiterals (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

. * + ? | ^ $ \ ( ) [ ] { }

represents "helo", "hello", "helllo", ...Regex'hel+o'

matches "hello"

is found in text "hello, world"

Page 9: ABAP Programming Comp361

SAP TechEd 08

9

© SAP 2008 / SAP TechEd 08 / COMP361 Page 17

Basic Regex Building Blocks

Basic regex building blocksThe dot " . " matches any single characterThe bar " | " lists alternativesParentheses " ( ) " group subexpressions

Examples

…a, bc, dea|bc|de

…a, bc, bda|b(c|d)

acd, abxd, acxxd, …abd, acxd, ac$d, …a(b|c.)d

…a, b, c, d, e, fa|b|c|d|e|f

ab, aabb, …aab, a1b, a%b, …a.b

RE Matches Doesn't Match

© SAP 2008 / SAP TechEd 08 / COMP361 Page 18

Adding Quantifiers to Regular Expressions

Matching multiple characters at onceAsterisk " * " denotes arbitrary repetition of previous character

Use " ( ) " to repeat more complex subexpressions

aa, aaa, aaaaa{2,4}between m and n repetitionsr{m,n}

ac, abcab?coptional rr?

ab+

ab*.*

Example

ab, abb, …

a, ab, abb, …(anything)

Matches

zero or more repetitions of rr*

one or more repetitions of rr+

RepresentsOp.

(empty), aa, b, aaaa, aab, bb, aaaaaa, …(aa|b)*

(anything with an odd number of characters).(..)*

Page 10: ABAP Programming Comp361

SAP TechEd 08

10

© SAP 2008 / SAP TechEd 08 / COMP361 Page 19

Sets and Classes

Sets define single character alternatives concisely

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

To include " [ ] ^ - \ ", use escape character " \ " Caution! Ranges such as [ä-ö] may be platform-dependent

Predefined classes provide cross-platform character subsets

[^0-9]

[^aA1]

[a-c0-9]

[aA1.]

a, b, c, or any digitRanges

any one character but a, A, or 1Negation

any one character but a digitMixed

a, A, 1, or .Literals

\l \L

[:lower:]

Lowercase

[:cntrl:][:space:][:word:][:digit:][:alpha:]

\d \D

Digits

\w \W

Alphanum

\s \S

Whitespace ControlLetters

© SAP 2008 / SAP TechEd 08 / COMP361 Page 20

Validating Data With Regular Expressions

Validating data with regular expressionsData input is valid if and only if it matches against regex pat

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

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

IF cl_abap_matcher=>matches( pattern = pattext = input )

= abap_true." accept valid input

ELSE." reject invalid input

ENDIF.

Page 11: ABAP Programming Comp361

SAP TechEd 08

11

© SAP 2008 / SAP TechEd 08 / COMP361 Page 21

Working With Regular Expressions

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

Check for valid symbols

Check for correct number of digits

Combining both checks: Naive approach

Combining both checks: Correct version

[\d\s\-]+

\d{15,16}

[\d\s\-]{15,16}

\s*(\d[\s\-]*){15,16}

\d = 1 digit\s = 1 white-

space

© SAP 2008 / SAP TechEd 08 / COMP361 Page 22

EXERCISE 1a

Exercise: Write simple regular expressions thatmatch all text samples shown in the left column anddo not match any text samples shown in the right column

System accessLog into system M55Start transaction SE38Run report ZTE08_REGEX_EX1

UsageClick on arrows to navigate between individual exercisesClick SHOW to display sample solution

Page 12: ABAP Programming Comp361

SAP TechEd 08

12

© SAP 2008 / SAP TechEd 08 / COMP361 Page 23

Using Regular Expressions in ABAP

RE support integrated into FIND and REPLACE statementsFinding first occurrence

Replacing all occurrences

Supports all known additions, e.g., IGNORING CASEAdditional support for FIND ALL OCCURRENCESAdditional support for searching internal tablesREs limited to CHARACTER MODE

FIND REGEX pattern IN textMATCH OFFSET off MATCH LENGTH len.

REPLACE ALL OCCURRENCES OF REGEX patternIN text WITH newREPLACEMENT COUNT cnt.

© SAP 2008 / SAP TechEd 08 / COMP361 Page 24

Searching With Regular Expressions

Searching returns leftmost-longest match within text

"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 withcat with Cath

hat thhat thus sat on th

sat on th

The cat with the hat sat on Cathy's mat.

FIND REGEX '.at' IN text ...

cathat

satCat

mat

Page 13: ABAP Programming Comp361

SAP TechEd 08

13

© SAP 2008 / SAP TechEd 08 / COMP361 Page 25

Getting Information From FIND and REPLACE

Obtain individual information by using additions

Contains information about the last match/replacement, if anySuccess indicated by sy-subrc and MATCH COUNTGet match text by offset and length access

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

FIND REGEX patternIN [TABLE] textMATCH COUNT cntMATCH LINE linMATCH OFFSET offMATCH LENGTH len.

text+off(len)

REPLACE REGEX patternIN [TABLE] text WITH newREPLACEMENT COUNT cntREPLACEMENT LINE linREPLACEMENT OFFSET offREPLACEMENT LENGTH len.

© SAP 2008 / SAP TechEd 08 / COMP361 Page 26

Using ABAP Regex Classes

ABAP Objects provides two classes for using REsRegex class cl_abap_regex

Stores preprocessed RE pattern for increasedperformanceShould be reused to avoid costly re-processing

Matcher class cl_abap_matcherCentral class for interaction with REsLinks text to regex objectStores copy of text to process (efficient forstrings, costly for fixed-length fields)Tracks matching and replacing within text

Using regex classes in ABAPCreate regex and matcher and interact with matcherUse static class methods of matcher as a shorthand

cl_abap_regex

a*b

cl_abap_matcher

$0_________

Page 14: ABAP Programming Comp361

SAP TechEd 08

14

© SAP 2008 / SAP TechEd 08 / COMP361 Page 27

Using Regex Classes for Matching

The matcher objects keeps track of the current match

1. Initially, there is no match

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

5. By calling replace_found( ), the match just found is replaced as specified

3. Information about the current match can be retrieved by calling get_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

match_________

© SAP 2008 / SAP TechEd 08 / COMP361 Page 28

Matcher Interface

get_submatch( index )get_length( [index] )

Querying

get_match( )get_offset( [index] )

replace_all( new )

find_all( )

match( )

Replacing

replace_found( new )

get_line( )

find_next( )

replace_next( new )

Finding

Page 15: ABAP Programming Comp361

SAP TechEd 08

15

© SAP 2008 / SAP TechEd 08 / COMP361 Page 29

Typical ABAP Code For Using Regex Classes

Set up matcher using factory

Process text with find and replace

DATA matcher TYPE REF TO cl_abap_matcher.

matcher = cl_abap_matcher=>create( pattern = 'a*b'text = mytext ).

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 30

Working With Submatches

Capturing parentheses store submatches for later reference

Match is subdivided into submatches and stored internally

One of the most useful features of REs!

Submatches can be …retrieved for further analysis/processingreferred to within patternreferred to within replacement

… required by 10/31 at the latest …(\d+)/(\d+)

10 ehtta3/1ybderi…

(\d+)/(\d+)

2nd submatch1st submatch

Page 16: ABAP Programming Comp361

SAP TechEd 08

16

© SAP 2008 / SAP TechEd 08 / COMP361 Page 31

Extracting Parts With Submatches

Submatches extract selected parts from a larger text

Use regex to locate information in larger text

Use subgroups to extract relevant parts only

Submatches easily retrieved with FIND additions

DATA: user TYPE string, pass TYPE string.

FIND REGEX '&login=(\w+)@(\w+)' IN urlSUBMATCHES user pass.

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

&login=frank@secret

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

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

&login=\w+@\w+

© SAP 2008 / SAP TechEd 08 / COMP361 Page 32

Avoiding Common RE Pitfalls (1)

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

Wrong approach for matching delimited parts

This greedily matches the largest possible substring

Solution: Include delimiters in negated character set

Some we <want>, and some we <don't>.

try to match HTML tag<.*>

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

Page 17: ABAP Programming Comp361

SAP TechEd 08

17

© SAP 2008 / SAP TechEd 08 / COMP361 Page 33

Avoiding Common RE Pitfalls (2)

Part delimiters may be escaped or quotedToo-relaxed approach for extracting ABAP string literals

This will stop at doubled quotes within character literals

Possible solution: List exceptions explicitly

Applies similarly to quoted delimiters: <tag attr="abc>xyz">

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

WRITE / `The ``good' news is ...`.

`([^`]|``)*`

<([^>]|"[^"]+")*>

© SAP 2008 / SAP TechEd 08 / COMP361 Page 34

Going Overboard

So you’d like to reject all invalid dates

Would you use this regex then?

Some things are best left to ABAP!

^(?=\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})?$

2/30/2006

Page 18: ABAP Programming Comp361

SAP TechEd 08

18

© SAP 2008 / SAP TechEd 08 / COMP361 Page 35

Summary – Efficient Processing of Text

Data types STRING and XSTRING support efficient text processingDynamic memory allocationSharing & Copy-on-Demand

Regular ExpressionsPowerful to describe patterns of textUsed for validation, searching, extracting of text

To learn moreRun ABAP report DEMO_REGEX_TOYCheck the ABAP online documentation

© SAP 2008 / SAP TechEd 08 / COMP361 Page 36

EXERCISE 1b

Exercise: Write a simple ABAP program thatreads all $ amounts from an input text andreplaces them by the doubled value

System accessLog into system M55Start transaction SE38Copy report ZTE08_REGEX_EX2_XX

Page 19: ABAP Programming Comp361

SAP TechEd 08

19

© SAP 2008 / SAP TechEd 08 / COMP361 Page 37

1. Efficient Processing of Textual Data1.1. Recab: String Data Types1.2. Regular Expressions

2. Extended Expressions2.1. Enhanced Expression Capabilities2.2. String Expressions

3. New Features of Internal Tables3.1. Dynamic WHERE Condition3.2. Secondary Keys

Agenda

© SAP 2008 / SAP TechEd 08 / COMP361 Page 38

Computational expressions only supported in COMPUTE statementArithmetic expressions (calculating numbers)Binary expressions (calculating bits)

Only pure logical expressions used in control statements

Expressions – Situation before NetWeaver 7.10

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

EXIT.ENDIF.

Swamping of code with helper variables

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

Page 20: ABAP Programming Comp361

SAP TechEd 08

20

© SAP 2008 / SAP TechEd 08 / COMP361 Page 39

New kind of computational expression: String expressionsComputational expressions supported in

various (input) operand positionslogical expressions

Expressions – Situation as of NetWeaver 7.10

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

Compact and efficient code with in-place expressions

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

ENDIF.

Computation as actual method parameter

Computation as operand in a logical expression

© SAP 2008 / SAP TechEd 08 / COMP361 Page 40

Examples for New Expression Positions

idx = lines( itab ).READ TABLE itab INDEX idx …

READ TABLE itabINDEX lines( itab ) …

tab = oref->tab( ).start = i + 1. end = n – 1.APPEND LINES OF tab

FROM start TO end TO t.

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

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

IF a + b > meth( c – d ).…

In logical expressions

len = strlen( txt ) - 1.DO len TIMES.

…DO strlen( txt ) – 1 TIMES.

Numeric input operand

regex = oref->get_pat( … ). FIND REGEX regex IN txt.

FIND REGEX oref->get_pat( … )IN txt.

Method call in generic input operands

Page 21: ABAP Programming Comp361

SAP TechEd 08

21

© SAP 2008 / SAP TechEd 08 / COMP361 Page 41

Expressions in Method Parameters

o->m( abs( i * 2 ) + 1 ). Unnamed actual parameter

cl=>m( p1 = i + 1 p2 = 2 ** j ). Named actual parameters

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

Any binary formal parameter accepts binary computation

cl=>m( pInt = 12 / 10pDec = 12 / 10 ).

Any numeric formal parameter accepts arithmetic computation

Formal parameter type contributes to calculation type (pInt ← 1, pDec← 1.2)

CREATE OBJECT o EXPORTING p = i + 1 .Instance constructor parameter

RAISE EXCEPTION TYPE lcxEXPORTING p = i + 1 . Exception constructor

parameter

o->m( cl=>m( p1 = o->i~m( 7 ) ) ). Parameter is method call

© SAP 2008 / SAP TechEd 08 / COMP361 Page 42

Method Call Chains

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

Chained method call

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

Terminal chained attribute access

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

Intermediate chained attribute access

Page 22: ABAP Programming Comp361

SAP TechEd 08

22

© SAP 2008 / SAP TechEd 08 / COMP361 Page 43

Extended Expressions – Pitfalls

No compiler optimizations, likecommon subexpression eliminationloop invariant extraction

⇒ programmer’s responsibility: temporary variables

ABAP is now also obfuscation enabled

But: Debugger support for complex expressionsDisplay of method return valueDisplay of intermediate computation results (by reducing the step size)

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 ) )

) ).

© SAP 2008 / SAP TechEd 08 / COMP361 Page 44

1. Efficient Processing of Textual Data1.1. Recab: String Data Types1.2. Regular Expressions

2. Extended Expressions2.1. Enhanced Expression Capabilities2.2. String Expressions

3. New Features of Internal Tables3.1. Dynamic WHERE Condition3.2. Secondary Keys

Agenda

Page 23: ABAP Programming Comp361

SAP TechEd 08

23

© SAP 2008 / SAP TechEd 08 / COMP361 Page 45

String Expressions

New kind of computational expressions: String ExpressionsConcatenations txt1 && txt2

String Templates |…Text…{ expression format = … }…Text…|

String ExpressionsUsed to create formatted or technical text (e.g. xml) convenientlyUsable in expression positions just like arithmetic or binary expressionsSubstitute masses of

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

New Built-In Functions23 functions returning a string result8 functions returning a non-string result4 new predicates on strings

© SAP 2008 / SAP TechEd 08 / COMP361 Page 46

DATA txt TYPE string.

CONCATENATE txt1 txt2 INTO txt.

CONDENSE txt.

txt = condense( txt1 && txt2 ).

In-place Concatenations

Concatenation operator

txt1 && txt2

Replaces CONCATENATE statement and many auxiliary variables

Page 24: ABAP Programming Comp361

SAP TechEd 08

24

© SAP 2008 / SAP TechEd 08 / COMP361 Page 47

String Templates

String Templates mix literal text with evaluated result of expressions

|…Text…{ expression format = … }…Text…|

LiteralText

EmbeddedExpression

Format Options

LiteralText

result = |{ txt width = 20align = left pad = pad }<---|.

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

align = center pad = pad }<---|.WRITE / result.result = |{ txt width = 20

align = right pad = pad }<---|.WRITE / result.

txt = „OOO“ and pad = „x“ yield

© SAP 2008 / SAP TechEd 08 / COMP361 Page 48

String Templates

String TemplatesEvaluation includes conversions, formatting and concatenatingDirectly supports the use of control characters (like “\n” for newline)Cannot stretch over multiple lines (use ‘&’ to concatenate across lines)

Replaces WRITE TO statement and many auxiliary variables

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

if intval < 0.cvar = '-'.write intval to cvar+1 no-sign left-justified no-grouping.s = cvar.

else.s = intval.

endif. s = |{ intval }|.

Page 25: ABAP Programming Comp361

SAP TechEd 08

25

© SAP 2008 / SAP TechEd 08 / COMP361 Page 49

Literal Text in String Templates

Literal TextConsists of all characters between ‘|’ and ‘{‘ resp. ‘}’ and ‘|’ (including spaces)May contain escaped characters or control characters

\|Character ‘|’

\\Character ‘\’

\{Character ’{’

\r

\n

\t

\}

Control characters

Tab (0x9)

Return (0xD)

Character ’}’

Newline (0xA)

Escape character ‘\’ needed for

© SAP 2008 / SAP TechEd 08 / COMP361 Page 50

Embedded Expressions in String Templates

Embedded ExpressionsIntroduced by ‘{‘ and ‘}’ within string templateMandatorily starts with an expression which result is converted to a string

Optional named parameters can be used to format the resulting string

Line breaks within the embedded expression are insignificant

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

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

Format options

Page 26: ABAP Programming Comp361

SAP TechEd 08

26

© SAP 2008 / SAP TechEd 08 / COMP361 Page 51

General Formatting Options

For all value types

{raw|upper|lower}

[character]

{left|right|center}

[integer number]

Alignment (left is default)align

Padding characterpad

Character casecase

Overall output widthwidth

© SAP 2008 / SAP TechEd 08 / COMP361 Page 52

Formatting Options for Numeric Values

For numeric values

Currency codeEntries from DB table TCURCcurrency

Output format for floating point numbers

Constants from CL_ABAP_FORMATstyle

Decimal format (raw is default)

{raw|user|environment}number

{yes|no}

[integer number]

[integer number]

{left|leftplus|leftspace|

right|rightplus|rightspace}

Exponentexponent

Number of decimal placesdecimals

Zero suppressionzero

Sign discipline(left is default)

sign

Page 27: ABAP Programming Comp361

SAP TechEd 08

27

© SAP 2008 / SAP TechEd 08 / COMP361 Page 53

Formatting Options for Date and Time Values

For date and time

Values from DB-table TTZZ-TZONE

space date space timeuser user settingiso data ‘T’ timeuser apply user setting

raw “182504”user apply user settingiso “18:25:04”environment apply locale setting

raw (“20080906”)user apply user settingiso (“2008-09-06”)environment apply locale setting

Time format

(raw is default)

time

Time stamp formattimestamp

Time zonetimezone

Date format

(raw is default)

date

© SAP 2008 / SAP TechEd 08 / COMP361 Page 54

String Processing before Release 7.10

Set of statements, e.g.,CONCATENATESPLITCONDENSEFIND SUBSTRING | REGEXREPLACE SUBSTRING | REGEX

Set of logical operators , e.g.,CS, NSCA, NA CP, NP

Set of built-in describing functions , e.g.,strlen( ... )charlen( ... )

Substring access via offset-length specification... text+off(len) ...

Page 28: ABAP Programming Comp361

SAP TechEd 08

28

© SAP 2008 / SAP TechEd 08 / COMP361 Page 55

New Built-in String Functions – Examples

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 = html regex = repl && `(?![^<>]*>)` with = `Treasure Island` occ = 0 ).

gives "<title>This is <i>Treasure Island</i></title>"

IF contains( val = emailmatch = `\w+(\.\w+)*@(\w+\.)+(\w{2,4})` ).

true if email contains a valid e-mail address

String processing is now directly available in expressions

© SAP 2008 / SAP TechEd 08 / COMP361 Page 56

Functions Returning a String (1)

substring_before( val = s (sub|regex) = s1 [occ = i1] [len = i2] )

substring_from( val = s (sub|regex) = s1 [occ = i1] [len = i2] )

substring_after( val = s (sub|regex) = s1 [occ = i1] [len = i2] )

shift_right( [val =] s [places = i1 | circular = i2 | sub = s1] )

Shifting Strings

shift_left( [val =] s [places = i1 | circular = i2 | sub = s1] )

substring_to( val = s (sub|regex) = s1 [occ = i1] [len = i2] )

segment( val = s index = i [sep = s1] )

substring( val = s [off = i1] [len = i2] )

match( val = text regex = regex [occ = occ] )

Extracting Substrings

Page 29: ABAP Programming Comp361

SAP TechEd 08

29

© SAP 2008 / SAP TechEd 08 / COMP361 Page 57

Functions Returning a String (2)

Transforming Strings

from_mixed( [val =] s [sep = c1] [case = c2] [min = i] )

to_mixed( [val =] s [sep = c1] [case = c2] [min = i] )

condense( [val =] s [del = s1] [from = s2] [to = c] )

repeat( val = s occ = i )

insert( val = s sub = s1 [off = i] )

to_lower([val =] s )

to_upper([val =] s )

reverse( [val =] s )

escape( val = s format = f )

replace( val = s (sub|regex) = s1 with = s2 [occ = i1] [case = c] )

translate( val = s from = s1 to = s2 )

© SAP 2008 / SAP TechEd 08 / COMP361 Page 58

Functions Returning a String (3)

oref->meth( boolc( …condition… )

).

if …condition… .temp_flag = 'X'.

else.temp_flag = ' '.

endif.oref->meth( temp_flag ).

Concatenates lines of <t> separated by <s>concat_lines_of( [table =] t [sep = s] )

Returns byte with bit i set to 1 if logical-expression is true else 0 (bit-set)

Returns ‘X’ if logical-expression is true else ‘ ’

Boolean Evaluations

boolc( logical-expression )

boolx( bit = i bool = logical-expression )

Concatenation of table lines

Page 30: ABAP Programming Comp361

SAP TechEd 08

30

© SAP 2008 / SAP TechEd 08 / COMP361 Page 59

Functions Describing Strings

count_any_of( val = s sub = s1 [off = i1] [len = i2] [occ = i3] )

Similarity of Strings (Returns Levenshtein distance)

distance( val1 = s1 val2 = s2 [max = i] )

find_any_not_of( val = s sub = s1 [off = i1] [len = i2] [occ = i3] )

find_any_of( val = s sub = s1 [off = i1] [len = i2] [occ = i3] )

find_end( val = s (sub|regex) = s1 [off = i1] [len = i2] [occ = i3] [case = c] )

count_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] )

find( val = s (sub|regex) = s1 [off = i1] [len = i2] [occ = i3] [case = c] )

Searching Substrings (Return the offset of the found location)

© SAP 2008 / SAP TechEd 08 / COMP361 Page 60

Predicate Functions on Strings

contains_any_not_of( val = s (sub|start|end) = s1 [off = i1] [len = i2] [occ = i3] )

contains_any_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] )

contains( val = s (sub|start|end|regex) = s1 [off = i1] [len = i2] [occ = i3] [case = c] )

Containing Substrings or Characters

Page 31: ABAP Programming Comp361

SAP TechEd 08

31

© SAP 2008 / SAP TechEd 08 / COMP361 Page 61

Summary – Extended Expressions

Extended use of expressionsSupported in many operand positions, especially for internal table statementsSeamless integrated in OO context (nested method calls, chaining)

String expressionsSimple, however very powerfulIntuitively use like arithmetic expressionsRich set of formatting optionsRich set of built-in string functions

To learn moreRun ABAP report DEMO_EXPRESSIONSCheck the ABAP online documentation

© SAP 2008 / SAP TechEd 08 / COMP361 Page 62

EXERCISE 2

Exercise: Write a simple ABAP program thatcreates an HTML page using string templates

System accessLog into system M55Start transaction SE38Copy report ZTE08_STRING_EX_XX

Page 32: ABAP Programming Comp361

SAP TechEd 08

32

© SAP 2008 / SAP TechEd 08 / COMP361 Page 63

1. Efficient Processing of Textual Data1.1. Recab: String Data Types1.2. Regular Expressions

2. Extended Expressions2.1. Enhanced Expression Capabilities2.2. String Expressions

3. New Features of Internal Tables3.1. Dynamic WHERE Condition3.2. Secondary Keys

Agenda

© SAP 2008 / SAP TechEd 08 / COMP361 Page 64

Need for a dynamic WHERE condition

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

Dynamic or generic language supportIntrospection 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

Page 33: ABAP Programming Comp361

SAP TechEd 08

33

© SAP 2008 / SAP TechEd 08 / COMP361 Page 65

Dynamic WHERE Condition since 7.10

One of these missing features is now available:

LOOP with dynamic WHERE condition

generic

dynamicgeneric

© SAP 2008 / SAP TechEd 08 / COMP361 Page 66

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 permittedThe 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.)

Page 34: ABAP Programming Comp361

SAP TechEd 08

34

© SAP 2008 / SAP TechEd 08 / COMP361 Page 67

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 68

Additional Features

Dynamic WHERE conditions can also handle the following constructsMethod calls and attribute accessArithmetic expressionsPredefined functionsAccess via data referencesDynamic WHERE condition has full secondary key support

Performance aspectsThe 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

Page 35: ABAP Programming Comp361

SAP TechEd 08

35

© SAP 2008 / SAP TechEd 08 / COMP361 Page 69

Exception handling

There is the exception CX_SY_ITAB_DYN_LOOP to handle incorrect WHERE conditions

© SAP 2008 / SAP TechEd 08 / COMP361 Page 70

DEMO

Page 36: ABAP Programming Comp361

SAP TechEd 08

36

© SAP 2008 / SAP TechEd 08 / COMP361 Page 71

1. Efficient Processing of Textual Data1.1. Recab: String Data Types1.2. Regular Expressions

2. Extended Expressions2.1. Enhanced Expression Capabilities2.2. String Expressions

3. New Features of Internal Tables3.1. Dynamic WHERE Condition3.2. Secondary Keys

Agenda

© SAP 2008 / SAP TechEd 08 / COMP361 Page 72

Why Secondary Keys for Internal Tables ?

Benefits from key tables (available since 4.0) Fast O(1) key access for hashed tables

size

time

O(1)

Page 37: ABAP Programming Comp361

SAP TechEd 08

37

© 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 tablesFast O(log n) key access for sorted tablesFast partial sequential processing for sorted tables (LOOP … WHERE optimization)

size

time

O(log n) O(1)

© SAP 2008 / SAP TechEd 08 / COMP361 Page 74

Why Secondary Keys for Internal Tables ?

Benefits from key tables (available since 4.0) Fast O(1) key access for hashed tablesFast O(log n) key access for sorted tablesFast partial sequential processing for sorted tables (LOOP … WHERE optimization)

Non-primary key access Slow O(n) runtime behaviorMight cause performance problemsTo be optimized by error prone hand-coded secondary key access

size

time

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

Low performancein productive context

Good perfomanceat first glance

Page 38: ABAP Programming Comp361

SAP TechEd 08

38

© SAP 2008 / SAP TechEd 08 / COMP361 Page 75

Evolution of Internal Tables

Since the beginning of ABAP in the 80ies

Counterpart to database tablesPaged memory allocation(high scalability)Fast index accessLinear key access (O(n))

Since mid of the 90ies

Fast key access(O(log n)) for sorted tablesO(1) for hash tables

High scalability due toTree data structures for the indices of sorted tablesGeneral purpose hash administration for hash tables

Coming with NetWeaver 7.1

Additional (multiple) secondary keys on arbitrary internal tablesLazy index update

Saves memory costsReduces runtime costs

Delayed index update for unique keys

Standard Tables Sorted/Hashed Tables Secondary Keys

© SAP 2008 / SAP TechEd 08 / COMP361 Page 76

Secondary Keys – Design Goals

Provide secondary key support analogously to databaseMultiple secondary keys are allowed

Contradictory key definitions are warned

Ease of useCanonical embedding into the ABAP language

Only 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

Explicit specification of the key to be used, instead

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

Page 39: ABAP Programming Comp361

SAP TechEd 08

39

© SAP 2008 / SAP TechEd 08 / COMP361 Page 77

Defining Secondary Keys

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

However, the key and its components to be used in a statement (READ, LOOP, …) can be specified dynamically

The 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 tableAccess kind: HASHED or SORTEDUniqueness kind: UNIQUE or NON-UNIQUE, where a hash key has to be uniqueKey components: either a user-defined list of componentnames or the pseudo-component TABLE_LINE

Reserved key names: PRIMARY_KEY and LOOP_KEY

Up to 15 secondary keys

© SAP 2008 / SAP TechEd 08 / COMP361 Page 78

Non-Unique vs. Unique Secondary Keys

Non-unique (sorted) secondary keysLazy 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 keysUniqueness is a semantic constraint, i.e. immediate response (exception/runtime error) if violated by atomic operations (INSERT, MOVE, SELECT, …)

Page 40: ABAP Programming Comp361

SAP TechEd 08

40

© SAP 2008 / SAP TechEd 08 / COMP361 Page 79

Defining Secondary Keys - Examples

© SAP 2008 / SAP TechEd 08 / COMP361 Page 80

Defining Secondary Keys –Redundancy Warnings

Syntax check warns if redundant key definitions are found

Page 41: ABAP Programming Comp361

SAP TechEd 08

41

© SAP 2008 / SAP TechEd 08 / COMP361 Page 81

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 82

DEMO

Page 42: ABAP Programming Comp361

SAP TechEd 08

42

© SAP 2008 / SAP TechEd 08 / COMP361 Page 83

Database table vs. Internal table:Comparison of secondary keys

Database tables:Optimizer decides which key to be takenIn 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 topof already existing entries with the same key values)

No implicit decision of the key to be taken possibleTherefore, explicit key specification required

© SAP 2008 / SAP TechEd 08 / COMP361 Page 84

Why is there no Implicit Optimization?

Smith23

Johnson31

Miller12

Nameyx

Results using primary key Results using secondary keyMiller Johnson

Smith Miller

Johnson Smith

different order

Page 43: ABAP Programming Comp361

SAP TechEd 08

43

© SAP 2008 / SAP TechEd 08 / COMP361 Page 85

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 updatedCatchable exception for a single INSERT operationRuntime error in case of block operations for DupRecs

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

© SAP 2008 / SAP TechEd 08 / COMP361 Page 86

Using Secondary Keys: READ with Respect to a Secondary Key

New addition “… USING KEY KeyName …”

New addition “… KeyName COMPONENTS …” for WITH clauses

Page 44: ABAP Programming Comp361

SAP TechEd 08

44

© SAP 2008 / SAP TechEd 08 / COMP361 Page 87

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 88

Using Secondary Keys:Other Statements Supporting Secondary Keys

Addition “… USING KEY KeyName …” for DELETE and MODIFY

Page 45: ABAP Programming Comp361

SAP TechEd 08

45

© SAP 2008 / SAP TechEd 08 / COMP361 Page 89

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 listedfor 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 canonly be achieved under these conditions.

© SAP 2008 / SAP TechEd 08 / COMP361 Page 90

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 usedRuntime error if this occurs in dynamically specified statements

Page 46: ABAP Programming Comp361

SAP TechEd 08

46

© SAP 2008 / SAP TechEd 08 / COMP361 Page 91

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

If no specific key is given, the compiler checksWhether 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 92

Tool Support:Debugging Support for Secondary Keys

Special features of the new ABAP debugger for secondary keys:Flush for outdated non-unique secondaryWatch 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

Page 47: ABAP Programming Comp361

SAP TechEd 08

47

© SAP 2008 / SAP TechEd 08 / COMP361 Page 93

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 94

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 watchpointdefinition

Page 48: ABAP Programming Comp361

SAP TechEd 08

48

© SAP 2008 / SAP TechEd 08 / COMP361 Page 95

DEMO

© SAP 2008 / SAP TechEd 08 / COMP361 Page 96

Incremental Key Changes

Delayed index update for incremental key changesNo index flush if key components are changed via pointer or reference accessUpdate 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 keysRequires debugging support (watch points on key changes) because there might be a significant time gap between the key changes and the index flush

Page 49: ABAP Programming Comp361

SAP TechEd 08

49

© SAP 2008 / SAP TechEd 08 / COMP361 Page 97

Unique key

……

517

516

……

Delayed Update of Unique Keys

© SAP 2008 / SAP TechEd 08 / COMP361 Page 98

Unique key

……

517

516

……

Delayed Update of Unique Keys

ref

Page 50: ABAP Programming Comp361

SAP TechEd 08

50

© SAP 2008 / SAP TechEd 08 / COMP361 Page 99

Unique key

……

517

517

……

Delayed Update of Unique Keys

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 100

Unique key

……

517

417

……

Delayed Update of Unique Keys

ref

Page 51: ABAP Programming Comp361

SAP TechEd 08

51

© SAP 2008 / SAP TechEd 08 / COMP361 Page 101

Unique key

……

517

417

……

Delayed Update of Unique Keys

ref

© SAP 2008 / SAP TechEd 08 / COMP361 Page 102

Active Key Protection

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

Generalization for secondary keysWithin 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

Page 52: ABAP Programming Comp361

SAP TechEd 08

52

© SAP 2008 / SAP TechEd 08 / COMP361 Page 103

Active Key Violation - Example

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

© SAP 2008 / SAP TechEd 08 / COMP361 Page 104

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 keysSyntax check support by redundancy warnings and performance hintsPerformance of existing programs can easily be improved by supplementing secondary keys (compatibility)Powerful delta management by lazy and delayed update handling

Page 53: ABAP Programming Comp361

SAP TechEd 08

53

© SAP 2008 / SAP TechEd 08 / COMP361 Page 105

Summary: Usage Scenarios

Optimal usage scenario for secondary keysVery 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 keysIf data integrity (uniqueness) is important

Applies also for small tables

Secondary keys should not be usedFor 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 106

EXERCISE 3

Page 54: ABAP Programming Comp361

SAP TechEd 08

54

© SAP 2008 / SAP TechEd 08 / COMP361 Page 107

Summary

Topics covered in this workshop

We introduced techniques for Processing text-based information using strings, regular expressions and string functionsWriting compact code using new expressions capabilitiesCreating well-formatted or technical text using string templatesGeneric programming using dynamic WHERE conditionsEfficiently managing large amounts of data stored in internal tables using secondary keys

© SAP 2008 / SAP TechEd 08 / COMP361 Page 108

Appendix

Page 55: ABAP Programming Comp361

SAP TechEd 08

55

© SAP 2008 / SAP TechEd 08 / COMP361 Page 109

ABAP Debugger – Memory Objects

Check memory consumption with the Memory Analysis Tool:Press button Special Tools Memory AnalysisBound memory: memory that will be available again for the current user session after freeing the tableReferenced memory: includes also memory reachable via references

© SAP 2008 / SAP TechEd 08 / COMP361 Page 110

ABAP Debugger – Memory Snap Shots

Make/compare memory snap shots using the Memory Analysis Tool:Press button Special Tools Memory AnalysisPress button to invoke the Memory Analysis Services dialogMake snap shots before and after flushing; invoke Memory InspectorCompare them by pressing the compare button

Page 56: ABAP Programming Comp361

SAP TechEd 08

56

© SAP 2008 / SAP TechEd 08 / COMP361 Page 111

Memory Costs for Secondary Keys

Memory costs (32/64 bit architectures):Basic admin costs

If the table has secondary keys at all ~ 32/48 bytes

If it has at least one non-unique secondary key (row id per line) 8 bytes / line

Costs per secondary key

Basic admin costs ~ 28/36 bytes

Sorted keys 4 - 6 bytes / line

Hashed keys ~ 18 bytes / line

Costs for lazy update

Additional index needed after DELETE/SORT 4 - 6 bytes / line

Costs for delayed update

Heavily depending on the number of changes …

Performance improvements to be paid by increased memory consumption

© SAP 2008 / SAP TechEd 08 / COMP361 Page 112

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 flushUnique keys

Immediate update costs at every insert operationUpdate costs caused by delayed (incremental) key changes

Total key maintenance :Sum of the costs for every table key

Avoid unnecessary key definitions

Page 57: ABAP Programming Comp361

SAP TechEd 08

57

© SAP 2008 / SAP TechEd 08 / COMP361 Page 113

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 114

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

Page 58: ABAP Programming Comp361

SAP TechEd 08

58

© SAP 2008 / SAP TechEd 08 / COMP361 Page 115

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 updatesContinuous learning presentations and demos to build expertise in each of the SAP NetWeaver platform componentsA personal SAP namespace

SAP NetWeaver Content Subscription: (available globally)An online library of continuous learning content to help build skills.

Starter Kit

Building Your Business with SDN Subscriptions

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 116

Fuel your Career with SAP Certification

Take advantage of the enhanced, expanded and multi tier certifications from SAP today!

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 that’s what matters most to customers.”*Conny Dahlgren, SAP Certified Professional

Page 59: ABAP Programming Comp361

SAP TechEd 08

59

© SAP 2008 / SAP TechEd 08 / COMP361 Page 117

Further Information

Related Workshops/Lectures at SAP TechEd 2008COMP209, News in ABAP Development, LectureCOMP267, ABAP Troubleshooting, WorkshopCOMP106, ABAP Performance and Trace Analysis, LectureCOMP269, Efficient Database Programming, LectureCOMP272, Memory Efficient ABAP Programming, WorkshopCOMP273, Test-Driven and Bulletproof ABAP Development, WorkshopCOMP274, Developing User Interfaces With Web Dynpro for ABAP, WorkshopCOMP275, State-of-the-Art ABAP -- Programming with ABAP Objects, WorkshopCOMP277, ABAP Development: Update Your Skills to SAP NetWeaver 7.0, Workshop

Related SAP Education and Certification Opportunitieshttp://www.sap.com/education/

SAP Public Web:SAP Developer Network (SDN): www.sdn.sap.comBusiness Process Expert (BPX) Community: www.bpx.sap.com

© SAP 2008 / SAP TechEd 08 / COMP361 Page 118

Thank you!

Page 60: ABAP Programming Comp361

SAP TechEd 08

60

© SAP 2008 / SAP TechEd 08 / COMP361 Page 119

Please complete your session evaluation.Be courteous — deposit your trash,

and do not take the handouts for the following session.

Thank You !

Feedback

© SAP 2008 / SAP TechEd 08 / COMP361 Page 120

Copyright 2008 SAP AGAll 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 Vervielfältigung dieser Publikation oder von Teilen daraus sind, zu welchem Zweck und in welcher Form auch immer, ohne die ausdrückliche schriftliche Genehmigung durch SAP AG nicht gestattet. In dieser Publikation enthaltene Informationen können ohne vorherige Ankündigung geändert werden.

Einige von der SAP AG und deren Vertriebspartnern vertriebene Softwareprodukte können 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 erwähnte SAP-Produkte und Services sowie die dazugehörigen Logos sind Marken oder eingetragene Marken der SAP AG in Deutschland und in mehreren anderen Ländern weltweit. Alle anderen in diesem Dokument erwähnten 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 können länderspezifische Unterschiede aufweisen.

Die in dieser Publikation enthaltene Information ist Eigentum der SAP. Weitergabe und Vervielfältigung dieser Publikation oder von Teilen daraus sind, zu welchem Zweck und in welcher Form auch immer, nur mit ausdrücklicher schriftlicher Genehmigung durch SAP AG gestattet. Bei dieser Publikation handelt es sich um eine vorläufige Version, die nicht Ihrem gültigen Lizenzvertrag oder anderen Vereinbarungen mit SAP unterliegt. Diese Publikation enthält nur vorgesehene Strategien, Entwicklungen und Funktionen des SAP®-Produkts. SAP entsteht aus dieser Publikation keine Verpflichtung zu einer bestimmten Geschäfts- oder Produktstrategie und/oder bestimmten Entwicklungen. Diese Publikation kann von SAP jederzeit ohne vorherige Ankündigung geändert werden.

SAP übernimmt keine Haftung für Fehler oder Auslassungen in dieser Publikation. Des Weiteren übernimmt SAP keine Garantie für die Exaktheit oder Vollständigkeit der Informationen, Texte, Grafiken, Links und sonstigen in dieser Publikation enthaltenen Elementen. Diese Publikation wird ohne jegliche Gewähr, weder ausdrücklich noch stillschweigend, bereitgestellt. Dies gilt u. a., aber nicht ausschließlich, hinsichtlich der Gewährleistung der Marktgängigkeit und der Eignung für einen bestimmten Zweck sowie für die Gewährleistung der Nichtverletzung geltenden Rechts. SAP haftet nicht für entstandene Schäden. Dies gilt u. a. und uneingeschränkt für konkrete, besondere und mittelbare Schäden oder Folgeschäden, die aus der Nutzung dieser Materialien entstehen können. Diese Einschränkung gilt nicht bei Vorsatz oder grober Fahrlässigkeit.

Die gesetzliche Haftung bei Personenschäden oder Produkthaftung bleibt unberührt. Die Informationen, auf die Sie möglicherweise über die in diesem Material enthaltenen Hotlinks zugreifen, unterliegen nicht dem Einfluss von SAP, und SAP unterstützt nicht die Nutzung von Internetseiten Dritter durch Sie und gibt keinerlei Gewährleistungen oder Zusagen über Internetseiten Dritter ab.

Alle Rechte vorbehalten.