Saturday, January 5, 2013

Regular Expressions (Regex) and its use in ABAP

Supported as of Release 7.00 Regular Expressions (Regex) are rarely found in ABAP. Have you ever heard something about Regex? We believe so. This article will give you a brief overview and present very good articles from SDN.


Even in ABAP Regular Expressions (Regex) is not a new issue. ABAP supports regular expressions as of Release 7.00, released to customers on Oct 24, 2005. Although not so new its use is rarely found in ABAP. One of reasons is that SAP has already provided other ways to search for patterns e.g. SEARCH txt FOR pattern and IF txt CP pattern.
But what is Regex after all?
Wikipedia
“In computing, a regular expression, also referred to as regex or regexp, provides a concise and flexible means for matching strings of text, such as particular characters, words, or patterns of characters. A regular expression is written in a formal language that can be interpreted by a regular expression processor, a program that either serves as a parser generator or examines text and identifies parts that match the provided specification.”
There is a very good tutorial about Regex at http://www.regular-expressions.info. We will skip the basics of Regex and go directly to its use in ABAP.
Using Regex in ABAP
Regex is more powerful than traditional SAP patterns and is commonly used for searching and validating text. ABAP supports Regex in the statements FIND and REPLACE and via the the classes CL_ABAP_REGEX and CL_ABAP_MATCHER.  There is an excellent article at SDN produced by Shaira Madhu with many more details of Regex in ABAP.
Let’s see some examples.
Example 1 – Tests if text starts with Hello (case sensitive)
DATA text TYPE string.
DATA moff TYPE i.
DATA mlen TYPE i.
text = `Hello World example`.
FIND REGEX '^Hello' IN text MATCH OFFSET moff MATCH LENGTH mlen.
IF sy-subrc = 0.
WRITE / text+moff(mlen).
ENDIF.
Example 2 – Removes example from the text only if it is the last word
DATA text TYPE string.
text = `Hello World example`.
REPLACE REGEX 'example$' IN text WITH ''.
IF sy-subrc = 0.
WRITE / text.
ENDIF.
Example 3 – Validates e-mail using the class CL_ABAP_MATCHER
DATA email   TYPE string VALUE `webmaster@sapignite`. "missing .com
DATA matcher TYPE REF TO cl_abap_matcher.
matcher = cl_abap_matcher=>create(
pattern = `\w+(\.\w+)*@(\w+\.)+(\w{2,4})`
text    = email ).
IF matcher->match( ) IS INITIAL.
MESSAGE 'Invalid e-mail' TYPE 'I' DISPLAY LIKE 'E'.
ENDIF.
Tip: For testing Regex without coding you can use the ABAP program DEMO_REGEX_TOY.
DEMO_REGEX_TOY screenshot
DEMO_REGEX_TOY screenshot
ABAP Geek 14 – Regular Expressions Made Easy
http://www.sdn.sap.com/irj/scn/weblogs?blog=/pub/wlg/15768

Free access to SAP HANA Sandbox for your first HANA experience

If you have been looking for getting access to SAP HANA Check out this article…


If you have been looking for getting access to SAP HANA to explore it Hands on.
This article would provide you necessary help to build your first data model in SAP HANA.
1. HOW TO GET FREE ACCESS TO SAP HANA
SAP has provided the HANA Sandbox System to learning purpose. You can register yourself  at  http://scn.sap.com/community/developer-center/hana   to request for your access.
You can also evaluate HANA One developer edition available on Amazon Cloud with nominal AWS hosting charges.
You can also try out few demos provided to get a feel of SAP HANA
2. YOUR FIRST EXERCISE IN SAP HANA. ( For Developers )
If you are an absolute beginner in HANA just like me, you can start with the first exercise
You can look for EIM162 Pdf :
Download
3. WANT TO GET YOURSELF CERTIFIED IN HANA ? –  C_HANAIMP_10
SAP has also introduced certification for associate level for SAP HANA lately. Find the below link for more details.
Now what else are are you waiting for Go ahead and get yourself HANAfied..
Drop me any comments if you are looking for any specific detail.

In LUV with SAP LUW !!!


Let’s Skip the Definition of LUV ( LOVE ) for shakespeare and jump to LUW.“LUW” (logical unit of work) is the span of time during which any database updates must be performed Either they are all performed ( committed ) , or  they are all thrown away ( rolled back ).
I have seen people always get confused between database LUW and SAP LUW.
Starting with DATABASE LUW :
The Open SQL statements INSERT, UPDATE, MODIFY, and DELETE allows you to program database changes that extend over several dialog steps. Even if you have not explicitly programmed a database commit, the implicit database commit that occurs after a screen has been processed concludes the database LUW. The following diagram shows the individual database LUWs in a typical screen sequence:
So let’s say we have a requirement where you want ALL or Nothing. In simple word at any step user can Rollback all the DB changes!!! That’s where SAP LUW comes into picture. What it does is , it bundles all the changes throughout the business transaction and commit them in single go to database when everything is fine.
sapluwhero
So we got three super heroes to help you out for bundling ☺
1. Bundling using Function Modules for Updates
If you call a function module using the CALL FUNCTION… IN UPDATE TASK statement, the function module is flagged for execution using a special update work process. This means that you can write the Open SQL statements for the database changes in the function module instead of in your program, and call the function module at the point in the program where you would otherwise have included the statements. When you call a function module using the IN UPDATE TASK addition, it and its interface parameters are stored as a log entry in a special database table called VBLOG.
The function module is executed using an update work process when the program reaches the COMMIT WORK statement. After the COMMIT WORK statement, the dialog work process is free to receive further user input. The dialog part of the transaction finishes with the COMMIT WORK statement. The update part of the SAP LUW then begins, and this is the responsibility of the update work process. The SAP LUW is complete once the update process has committed or rolled back all of the database changes.
2. Bundling Using Subroutines
The statement PERFORM ON COMMIT calls a subroutine in the dialog work process. However, it is not executed until the system reaches the next COMMIT WORK statement. Here, as well, the ABAP statement COMMIT WORK defines the end of the SAP LUW, since all statements in a subroutine called with PERFORM ON COMMIT that make database changes are executed in the database LUW of the corresponding dialog step.
3. Bundling Using Function Modules in Other R/3 Systems
Function modules that you call using CALL FUNCTION… IN BACKGROUND TASK DESTINATION… are registered for background execution in another R/3 System when the program reaches the next COMMIT WORK statement (using Remote Function Call). After the COMMIT WORK, the dialog process does not wait for these function modules to be executed (asynchronous update). All of the function modules that you register in this way are executed together in a single database LUW. These updates are useful, for example, when you need to maintain identical data in more than one database.
Now sometimes we need to start our own local LUW inside already running LUW without effecting the main LUW.Something like..
sapluw
Let’s discuss possible ways to do that???
1. How about calling a Function module in update task??
It will start a new LUW, but you can’t commit your LUW inside it, As you can’t write commit work inside your LUW.
2. How about Calling a Function module in Background task something like :
REPORT ZTEST_MAIN.

TABLES : ZEMPLOYEE.
ZEMPLOYEE-EMPLOYEE_ID = 0034.
ZEMPLOYEE-EMPLOYEE_FNAM = ‘10/07/2011′.
ZEMPLOYEE-EMPLOYEE_LNAM = ‘Main’.
CALL FUNCTION ‘ZTEST_UPDATEFM1′ IN UPDATE TASK
EXPORTING
ZEMPLOYEE = ZEMPLOYEE.

call function ‘ZTEST_UPDATEFMJOB’ IN BACKGROUND task AS SEPARATE UNIT DESTINATION ‘NONE’
exporting ZEMPLOYEE = ZEMPLOYEE.
write : / ‘hello’.
Advantages: It will start a separate LUW But To trigger ZTEST_UPDATEFMJOB in Background needs a commit work in the calling program. So again it’s not our requirement.
3. How about SUBMIT and RETURN.
REPORT ZTEST_SUBMIT.
TABLES : ZEMPLOYEE.
ZEMPLOYEE-EMPLOYEE_ID = 0034.
ZEMPLOYEE-EMPLOYEE_FNAM = ‘10/07/2011′.
ZEMPLOYEE-EMPLOYEE_LNAM = ‘Main’.

CALL FUNCTION ‘ZTEST_UPDATEFM1′ IN UPDATE TASK
EXPORTING
ZEMPLOYEE = ZEMPLOYEE.
SUBMIT ZTEST_SUBMIT1 AND RETURN. “a new LUW
write : / ‘hello’.
Advantage: perfect!!!! But issue is passing of the data to Submitted report. You might need to use EXPORT TO MEMORY or IMPORT TO MEMROY if you want to pass tables and etc. To the called program (If its RANGE tables or normal parameters that fine) u can use VIA SELECTION-SCREEN option.

4. Use parallel processing
It’s like calling Remote enabled Function module in asynchronous task. Check out the below article to know more about it.
Note: Theory says that calling a Remote enabled Function module in separate task does implicit commit and complete the current SAP LUW.But till now practical does not says it.. ☺ !!!!! so Try it out for yourself.
Please feel free to comment on this and let’s discuss more about LUW .

Have you ever seen Standard SAP ABAP code like these !?!?!?


Standard ABAP code….LOL!!!!!!!!!!
Check the comments in the following programs!!!!!!!!!!!!!!
After Reading this you will not have any complains on your own coding standards as especially Not updating proper comments!
Please try checking in your respective DEV systems and you will be surprised for sure.
1: CRM_GET_KEYDATA
im1
2: RSINFF01
im2
3: RPUWUPDB
im3
4: CRWBD0_START_BATCH
im4
5:RCIFCUST
im6
6: LV61BMES
im5
7: LATPCFA6
im7
8: MV45AF0R_REFRESH_HELP_VALUES
im8
9:RSSOAPUT
im10
10: GET_DATA
im9
11: LCORFF1K
im11
12: /DSD/SL_FSRSEL_PROCESS
im12
13: CONTROL_CREATE
im13
14: LTHMEX_FRONTENDF05
im14
15: MV45AF0T_T001W_SELECT
im15
16: LCPBRTOP
im16
17: HR_GBSSP_DAY_CHECKS
im17
18: NEXT_NODE
im18
19: LSMIGR_MSSF02
im19
20: SHOW_DEMO
im20

Best practices working with SAP ABAP : DATABASE

Looking For best practices to follow while working with database in sap abap.check out this article.


Here are the few best practices you should follow to improve the performance while working with Database.
Buffering of Data (Useful but wrong Buffering can be harmful)
Defining a table as buffered (SE11) can help in improving the performance but this has to be used with caution.


  • Buffering of tables leads to data being read from the buffer rather than from table. Buffer sync with table happens periodically, only if something changes which is happen rarely.
  • If this table is a transaction table chances are that the data is changing for particular selection criteria, therefore application tables are usually not suited for table buffering.Using table buffering in such cases is not recommended.

    • Customizing data and Master Data should be buffered from DB to Application layer. This will help in reducing the number of hits to the database and enhance performance.
    • In case of Standard master data, try using already available standard Function Modules to fetch data with buffering.
    Following statements cannot be used with a buffered table. In such cases, buffer is bypassed. These are:
    - SELECT DISTINCT
    - ORDER BY
    - GROUP BY
    - HAVING
    - Nested Queries
    - JOIN Queries

    Indexing ( its kind of useful if you are not creating it just for name sake , But at the same time time-consuming if its created without proper research ) Creation of Index for improving performance should not be taken without thought. Index speeds up the performance but at the same time adds two overheads namely; memory and insert/append performance.
    When INDEX is created, memory is used up for storing the index and index sizes can be quite big on large transaction tables!
    When inserting new entry in the table, all the indexes are updated. More index more time. More the amount of data, bigger the indices, larger the time for updating all the indices
    ∙ Table should not have more than 2 secondary indexes if the data class is APPL1.
    ∙ Table should not have more than 4 secondary indexes if the data class is APPL0.
    ∙ A secondary index should not have more than 4 fields.
    ∙ Table should not have a unique secondary index.
    Use secondary index / Create secondary index if accessing a database table with non-key fields depending on the frequency of usage and volume of data accessed.


    JOIN Vs. FOR ALL ENTRIES
    JOINS are recommended to be used till 5 joins. If the JOIN is being made on fields which are key fields in both the tables, it reduced program overhead and increases performance.
    So, if the JOIN is between two tables where the JOINING KEYS are key fields JOIN is recommended over FOR ALL ENTRIES.
    Check that the internal table used in FOR ALL ENTRIES is NOT empty as this will retrieve all entries from the table


    HAVING clause in a SELECT statement
    In a SELECT statement, the HAVING clause allows you to specify a logical condition for the groups in a GROUP-BY clause.
    Effective use of the having clause can reduce the set of data transferred from the database to the application server.
    When the having clause is used, the aggregates and groups are constructed in the database instead of the application server, thereby reducing the resulting set.
    For example, if application requires cumulative sales figures for a month in APJ.
    Care needs to be taken while selecting a proper match ;-)
    SELECT *
    Wherever possible, fields should be specified rather than SELECT *.

    SELECT * Vs. SELECT SINGLE *
    If you are interested in exactly one row of a database table or view, use the SELECT SINGLE statement instead of a SELECT * statement.
    SELECT SINGLE requires one communication with the database system whereas SELECT * requires two.
    SELECT SINGLE Vs SELECT … UP TO 1 ROWS?
    SELECT SINGLE and SELECT UP TO n ROWS return the first matching row/rows for the given condition. It may not be unique, if there are more matching rows for the given condition.
    In order to check for the existence of a record then it is better to use SELECT SINGLE than using SELECT … UP TO 1 ROWS since it uses low memory and has better performance.With ORACLE database system, SELECT SINGLE is converted into SELECT … UP TO 1 ROWS, thus they are exactly the same in that case.
    The only difference is the ABAP syntax prevents from using ORDER BY with SELECT SINGLE, but it is allowed with SELECT … UP TO 1 ROWS.
    Thus, if several records may be returned and we want to get the highest record for example, SELECT SINGLE cannot be used, but SELECT … UP TO 1 ROWS WHERE … ORDER BY … may be used.
    Accessing Pool and Cluster Tables
    When accessing pool and cluster tables, these should be accessed using the full primary key

    SELECT query in a loop
    Avoid placing a ‘SELECT’ or ‘SELECT SINGLE’ in a loop to minimize the number of database requests

    SELECT.. INTO Vs. SELECT..INTO CORRESPONDING FIELDS OF..
    Use the latter if:
    ∙ the fields are needed in a different order the not all fields are needed and INTO does not work because gaps would appear.


    SELECT….INTO Vs. SELECT…ENDSELECT….APPEND
    It is more efficient to use the former to pull the data from DB to internal table rather than performing APPEND within SELECT…ENDSELECT.
    Bad Example:
    SELECT * FROM T006 INTO X006.
    APPEND X006.
    ENDSELECT.
    Good Example:
    SELECT * FROM T006 INTO TABLE X006.

    SELECT *…WHERE <Condition>
    The number of records retrieved should be limited using the ‘WHERE’ clause rather than selecting and using the ‘CHECK’ statement.
    Fields should be listed in the WHERE clause in the same order as they appear in the table.
    Bad Example:
    SELECT * FROM SBOOK.
    CHECK: SBOOK-CARRID = ‘LH’ AND SBOOK-CONNID = ’0400′.
    ENDSELECT.
    Good Example:
    SELECT * FROM SBOOK WHERE CARRID = ‘LH’ AND CONNID = ’0400′. ENDSELECT.



    ORDER BY clause Vs. Internal Table Sorting
    Using SORT statements in place of ORDER BY clause in SELECT statement is more efficient.
    Sorting will happen in Application layer on the internal table which will be much faster as compared to search in DB using ORDER BY clause.
    Perform ORDER BY clause should NOT be used with non-key and non-index fields.
    Do not use SORT statements within a loop.


    Aggregate Functions
    Make use of aggregate functions while writing Select Query rather than using loops on internal tables to find Max. Value for example as this is more efficient.

    Bad Example:
    C4A = ’000′.
    SELECT * FROM T100 WHERE SPRSL = ‘D’ AND ARBGB = ’00′.
    CHECK: T100-MSGNR > C4A.
    C4A = T100-MSGNR.
    ENDSELECT.
    Good Example:

    SELECT MAX( MSGNR ) FROM T100 INTO C4A WHERE SPRSL = ‘D’ AND ARBGB = ’00′.


    SELECT DISTINCT Vs. SELECT….SORT….DELETE ADJACENT….
    Avoid using SELECT DISTINCT clause. Instead SORT the internal table and then DELETE the adjacent duplicates as this is more efficient.

    Identical Selects
    Avoid using identical selects (SELECT with same parameters and WHERE clause) multiple times in a program flow. This causes hits to DB which can be reduced with biuffering
    Consider buffering of data from SELECT statement and re-using the same information elsewhere instead of querying the database again with same parameters.


    Existence Checks
    If you are interested if there exists at least one row of a database table or view with a certain condition, use the Select … Up To 1 Rows statement instead of a Select-Endselect-loop with an Exit.
    If all primary key fields are supplied in the Where condition you can even use Select Single. Select Single requires one communication with the database system, whereas Select-Endselect needs two.