Documente Academic
Documente Profesional
Documente Cultură
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 TechEd 08
Learning Objectives
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
Agenda
2. Extended Expressions
2.1. Enhanced Expression Capabilities 2.2. String Expressions
SAP TechEd 08
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
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
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
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
A B C D E F G H I J
str = 'first'.
f i r s t
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
main memory
SAP 2008 / SAP TechEd 08 / COMP361 Page 8
SAP TechEd 08
String Sharing
references + headers
Restrictions on Substrings
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
SAP TechEd 08
Advantages of strings
Storage
allocated dynamically
DATA custname TYPE c LENGTH ??. READ DATASET dset INTO line.
Common
DATA customers TYPE TABLE OF cust_record. " cust_record = ( name, street, city )
Trailing
DATA c80 TYPE c LENGTH 80 VALUE 'hello'. CONCATENATE c80 'world' INTO c80.
SAP 2008 / SAP TechEd 08 / COMP361 Page 11
Agenda
SAP TechEd 08
Checking
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
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
SAP TechEd 08
<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.
(characters) Operators (meta characters) . * + ? | ^ $ \ ( ) [ ] { } Prepending " \ " turns operators into literals
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
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,
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 TechEd 08
a, A, 1, or . a, b, c, or any digit any one character but a, A, or 1 any one character but a digit
include " [ ] ^ - \ ", use escape character " \ " Ranges such as [-] may be platform-dependent
Caution!
Alphanum [:word:] \w \W
Lowercase [:lower:] \l \L
Whitespace [:space:] \s \S
Control [:cntrl:]
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
10
SAP TechEd 08
Design regex that matches given input if input resembles a plausible credit card number
Check
Check
Combining
Combining
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
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
sat
Cat
mat
12
SAP TechEd 08
REPLACE REGEX pattern IN [TABLE] text WITH new REPLACEMENT COUNT cnt REPLACEMENT LINE lin REPLACEMENT OFFSET off REPLACEMENT LENGTH len.
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
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
$0
regex and matcher and interact with matcher static class methods of matcher as a shorthand
13
SAP TechEd 08
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
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( )
14
SAP TechEd 08
Set
DATA matcher TYPE REF TO cl_abap_matcher. matcher = cl_abap_matcher=>create( pattern = 'a*b' text = mytext ).
Process
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
1st submatch
One
2nd submatch
Submatches can be
retrieved referred
15
SAP TechEd 08
Use
Submatches
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
Matches are greedy " .* " usually matches way too much
Wrong
This
greedily matches the largest possible substring Some we <want>, and some we <don't>.
Solution:
16
SAP TechEd 08
will stop at doubled quotes within character literals WRITE / `The ``good' news is ...`.
Possible
Applies
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
Regular Expressions
Powerful to describe patterns of text Used for validation, searching, extracting of text
To learn more
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
Computational
Only
use of few built-in functions and functional methods in very few operand positions only
19
SAP TechEd 08
New
= n.
set of built-in functions including string and predicate functions Functional methods allowing nested and chained method calls
Compact
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
20
SAP TechEd 08
Any numeric formal parameter accepts arithmetic computation Formal parameter type contributes to calculation type (pInt 1, pDec 1.2)
Any binary formal parameter accepts binary computation Instance constructor parameter Exception constructor parameter
cl=>m1( )->m2( ).
Terminal chained attribute access
21
SAP TechEd 08
Display of method return value Display of intermediate computation results (by reducing the step size)
Agenda
2. Extended Expressions
2.1. Enhanced Expression Capabilities
22
SAP TechEd 08
String Expressions
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
23 functions returning a string result 8 functions returning a non-string result 4 new predicates on strings
In-place Concatenations
DATA txt TYPE string. CONCATENATE txt1 txt2 INTO txt. CONDENSE txt. txt = condense( txt1 && txt2 ).
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
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 }|.
if intval < 0. cvar = '-'. write intval to cvar+1 no-sign left-justified no-grouping. s = cvar. else. s = intval. s = |{ intval }|. endif.
24
SAP TechEd 08
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 \\ \| \{ \}
Embedded Expressions
Introduced by { and } within string template Mandatorily starts with an expression which result is converted to a string
25
SAP TechEd 08
26
SAP TechEd 08
time
timestamp
timezone
Time zone
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
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
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
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] )
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 ).
29
SAP TechEd 08
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
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] )
30
SAP TechEd 08
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
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
2. Extended Expressions
2.1. Enhanced Expression Capabilities 2.2. String Expressions
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
32
SAP TechEd 08
generic
generic
dynamic
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.
33
SAP TechEd 08
Additional Features
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
34
SAP TechEd 08
Exception handling
DEMO
SAP 2008 / SAP TechEd 08 / COMP361 Page 70
35
SAP TechEd 08
Agenda
2. Extended Expressions
2.1. Enhanced Expression Capabilities 2.2. String Expressions
time
size
O(1)
36
SAP TechEd 08
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)
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
O(n) runtime behavior cause performance problems To be optimized by error prone hand-coded secondary key access
Might
size
O(n) O(log n) O(1)
37
SAP TechEd 08
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
Contradictory
Ease of use
Canonical Only
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)
38
SAP TechEd 08
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
to 15 secondary keys
No memory costs if not used Thus, perfectly suitable to tune existing programs
is a semantic constraint, i.e. immediate response (exception/runtime error) if violated by atomic operations (INSERT, MOVE, SELECT, )
39
SAP TechEd 08
40
SAP TechEd 08
ABAP Dictionary (SE11) New tabstrip Secondary Key Up to 15 secondary table keys allowed
DEMO
SAP 2008 / SAP TechEd 08 / COMP361 Page 82
41
SAP TechEd 08
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:
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
x 2 1 3
y 1 3 2
42
SAP TechEd 08
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)
43
SAP TechEd 08
44
SAP TechEd 08
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.
Syntax error if it can be statically decided that a key cannot be used Runtime error if this occurs in dynamically specified statements
45
SAP TechEd 08
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)
Flush for outdated non-unique secondary Watch points on secondary key changes Debugger symbol key_status( ItabName KeyName )
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
46
SAP TechEd 08
47
SAP TechEd 08
DEMO
SAP 2008 / SAP TechEd 08 / COMP361 Page 95
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
48
SAP TechEd 08
Unique key
16 17
5 5
Unique key
16 17
5 5
ref
49
SAP TechEd 08
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
Unique key
17 17
4 5
ref
50
SAP TechEd 08
Unique key
17 17
4 5
ref
Key components of sorted or hash tables are write protected, i.e. no changes via pointers or references possible (runtime error)
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
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
51
SAP TechEd 08
The following coding shows an example for an active key violation resulting in the runtime error ITAB_ACTIVE_KEY_VIOLATION
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
52
SAP TechEd 08
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
For small tables (less than 50 lines) because of administrative and memory overhead If modifications dominate the table processing
EXERCISE 3
SAP 2008 / SAP TechEd 08 / COMP361 Page 106
53
SAP TechEd 08
Summary
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
Appendix
SAP 2008 / SAP TechEd 08 / COMP361 Page 108
54
SAP TechEd 08
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
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
55
SAP TechEd 08
If the table has secondary keys at all If it has at least one non-unique secondary key (row id per line)
Additional index needed after DELETE/SORT Costs for delayed update Heavily depending on the number of changes
4 - 6 bytes / line
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
56
SAP TechEd 08
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
Due to the delayed update feature, this may lead to a DupRec error when the next table statement is exceuted
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
Their primary types are shareable They have the same secondary keys
57
SAP TechEd 08
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
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
Teams with certified architects and developers deliver projects on specification, on time, and on budget more often than other teams.
2008 IDC Certification Analysis
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
Thank you!
59
SAP TechEd 08
Thank You !
SAP 2008 / SAP TechEd 08 / COMP361 Page 119
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