Iterating On a Table Using Field Symbols

Say you have a Table called “table_name”, of line type “table_row”, and you wish to iterate on it and perhaps change the rows while you’re iterating. You can do it in ABAP using field symbols.
First, you need to define the field symbol. In our example it’s called “symbol_name”


FIELD-SYMBOLS <symbol_name> TYPE table_row.


Now, you can iterate over the table, assigning each row to the field symbol


LOOP AT table_name ASSIGNING <symbol_name>.
...
ENDLOOP



On each iteration, you can manipulate the table using the field symbol. Any change done to the field symbol is also done on the table. It’s like using a pointer in C or a reference variable in C++.

Important note: When using field symbols on sorted or hashed table, then you may not change the key fields of these tables. Doing so results in a runtime error. The logic is simple: changing the key will change the sorting order or hashing order of the table, and since you’re in mid-iteration, it may cause you to re-iterate on these rows. You Java developers out there may be familiar with this concept, as it also exists in Java.

You can read more about field symbols at the following SAP help link.

Read more...

The difference between INSERT, UPDATE, and MODIFY

Here's a very common syntactic question: What's the difference between INSERT, UPDATE, and MODIFY?
The answer is plain and simple:

INSERT - inserts a new record. INSERT expects that a record with the required key does NOT exist in the table. Therefore, if a record with the same key already exists, a runtime error occurs. For more details on INSERT, visit here.

UPDATE - update an existing record. UPDATE expects that a record with required key exists in the table. If a record with the required key does not exist, it issue an error (sy-subrc is 4). For more details on UPDATE, visit here.

MODIFY - acts like a combination of INSERT and UPDATE. If a record with the specified key does not exist, it adds it to the table. If a record with the specified key does exist, it modifies it. So MODIFY actually acts like "Insert or change record". To read more about MODIFY, visit here.

To summarize:
INSERT - adds a new record to the table. If the row (key) exists, issues an error.
UPDATE - updates an existing record to the table. If the row (key) does not exist, issues an error.
MODIFY - If the key exists, modifies the record. If the key does not exist, adds the record to the table.

Read more...

Reflection in ABAP

Say you want to create an instance of a class that implements a certain interface, but you won’t know the name of the class you want to create until runtime. In Java or .NET you would have used the reflection mechanism, but can you handle this case in ABAP?
Apparently, you can.
Here’s a short code snippet showing how:



DATA: iv_classname TYPE seoclsname.
DATA: iv_interface TYPE REF TO IF_INTERFACE_NAME.
DATA: gr_error TYPE REF TO cx_dynamic_check.
DATA: gv_message TYPE string.

iv_classname = 'CL_CLASSNAME'.

TRY .
CREATE OBJECT iv_interface TYPE (iv_classname).

CATCH cx_sy_create_object_error INTO gr_error.
gv_message = gr_error->get_text( ).
WRITE :/1 gv_message.

CATCH cx_sy_dyn_call_param_missing INTO gr_error.
gv_message = gr_error->get_text( ).
WRITE :/1 gv_message.

ENDTRY.



Let’s have a look at the code.
In the first four rows, you define several variables data types.
iv_classname hold the name of the class (that’s the name which will be known only in runtime)
iob_object – a reference to an interface that the class you’ll instantiate implements.
The other two variables are for error handling purposes.
Now, you use the CREATE OBJECT ABAP statement.


CREATE OBJECT iv_interface TYPE (iv_classname).



Note that had you known the class name during compile time, you could use the following statement:


CREATE OBJECT iv_interface TYPE CLASSNAME.


The difference? No parenthesis, plus you give the class name instead of a string containing the class name.
Let’s move on. In case the class does not exist on the system you’re running (or your provided a wrong class name), you’ll get the exception CX_SY_CREATE_OBJECT_ERROR, saying that the class you’re trying to instantiate couldn’t be found. In case there are missing parameters, you will get a CX_SY_DYN_CALL_PARAM_MISSING exception. Note that in the example above no parameters were passed to the constructor, but in case there are parameter, the creation statement should look as follows.


CREATE OBJECT iv_interface TYPE (iv_classname) EXPORTING param1 = value1 param2 = value2.


You now know a little bit about dynamically instantiating objects in your code – a great way to implement dynamic and extensible factory methods!

Read more...

Using ABAP Exception classes with Message classes (Part 2 of 2)

In the previous post, we created a simple ABAP exception class that uses a Message Class. Now let’s see how we can use this class. It’s strongly recommended that you read part one before continuing.

The statement for raising (or throwing) an exception class that uses a Message class looks as follows:

raise exception type CX_DB_ERROR
exporting TEXTID = CX_DB_ERROR=>WRITE_ERROR
TABLENAME = ‘SPFLI’.


Let’s analyze this statement. First, we state the type of the exception, which is CX_DB_ERROR (that’s the exception that we created in the previous post). Next, we’re passing the parameters to the exception.

The first parameter answers the question – “What is the message we want to display?” It states the key of the text that we want to insert. Since we want to display a text for a “database write error”, we pass the key WRITE_ERROR (Remember it from last time? We created it on step 6).

The second parameter answers the question “What are the parameters needed for the message we want to display?” If you remember, our message had one parameter, the table name, so that we could imply that the write error occurred on this or that table. So here we pass the name of the table, in this example it’s the famous SPFLI.

So far we’ve looked on how to throw the exception. Now let’s take a look at the code for catching the exception.


data OREF type ref to CX_ROOT.data TEXT type STRING.

try.

... “Some method that throws CX_DB_ERROR

catch CX_DB_ERROR into OREF.

TEXT = OREF->GET_TEXT( ).

endtry.


In this simple code example, we catch the exception CX_DB_ROOT into a variable called OREF. We then extract the exception text into the variable TEXT by using the GET_TEXT() method.

At the end of this code execution, the variable TEXT should hold the following string:

“An error occurred when writing to table SPFLI”.

Note: There is another parameter which is commonly passed when creating an exception. It is called PREVIOUS, and it’s used to wrap exception in case of an exception chain. Those of you who have experience with Java or .NET are probably familiar with this concept. To all the others, don’t worry – we’ll mention exception chains later on.

Read more...

Using ABAP Exception classes with Message classes (Part 1 of 2)

We’ve talked about Exception Classes, and we’ve talked about Message Classes. Now let’s see how we can combine these two together.

Let’s take a scenario, in which you have an exception that is thrown whenever a database error occurs in your program. Let’s call this exception class CX_DB_ERROR. We want our exception to display various messages that can also be translated later on to different languages. For example, “Error when writing to database” or “Error when reading from database”. So let’s combine ABAP Exception and Message classes.

1. First, create a message class through SE91. For this example’s sake, let’s call it CM_DATABASE_MESSAGES

2. Add a few messages to the message class. For our example, let’s add the message: “An error occurred when writing to table &1”. &1 indicates that a parameter would be inserted to the message. This parameter would be the name of the table that caused the error. We’ll get back to this in a few minutes.

3. Now open SE80 and create the exception class CX_DB_ERROR .

4. Remember that our message from step 2 states which table caused the error? Now’s the time to add this parameter. So click on the “Attributes” tab, and add an attribute for the table name. Let’s call it TABLE_NAME, and give it the type STRING.

5. Next, click on the “Texts” tab.

6. Enter a key to the message you would like to display on your exception class. In our example, let’s add the key WRITE_ERROR, indicating an error occurred when writing to the database.

7. Click on the “Message Text” button.

8. A new dialog opens, titled “Assign Attributes of an Exception Class to a Message”.

9. In the field “Message Class”, insert the name of the Message Class associated with your exception class. Let’s insert the class CM_DATABASE_MESSAGES, which we created earlier.

10. Now we need to choose the message number. Click on the choice button and choose the message “An error occurred when writing to table &1”. The number of the message should now appear in the field (as we created only one message in our example, it should be 000).

11. Now, you have to choose attributes that would be associated with the parameter &1. Click on the drop down list button, and choose the TABLE_NAME attribute we created earlier.

12. Save everything and activate.

You’ve just finished creating an exception class that uses a message class. In the next post, I’ll show you how to use the exception class with the message.

Read more...

Initializing an Internal Table

In case you have an internal table “itab”, and you wish to initialize it (clear it), here are some common statements:

CLEAR itab.
This command clears the header of a table, but keeps its content. The initial memory allocated for the table remains reserved.
(If you don’t remember what a header line is, you can find out here or here).

CLEAR itab[].
The content of the table is released, and the header line is not (kind of the opposite of the CLEAR command).

REFRESH itab.
Clears the content of the internal table completely. The initial memory allocated for the table remains reserved . The header content is also cleared.

FREE itab.
Initializes the internal table and releases its entire memory space, including the initial memory requirement. So using free deallocates memory.

For more information visit the SAP Help. Also, the following blog has nice examples of what happens to an internal table and its header by using each of the commands above.

Read more...

Updating a Database Table from an Internal Table

In case you have an internal table, and wish to use it in order to update a database table, use the following statements:

UPDATE dbtab FROM TABLE itab

Or

INSERT dbtab FROM TABLE itab

Where dbtab is the name of the database table, itab is the name of the internal table
Note: A common mistake would be to omit the word TABLE from the above statement. Doing this will yield the following error:
“You cannot use an internal table as a work area”.

Read more...

Message Classes

Messages are text which you use in your programs in order to communicate with your users. For example, you wish to state that some process completed successfully, or, you wish to declare an error.

Message classes are containers of messages. Each message has a number and a value. Parameters can also be added to message classes, just as could be achieved by string formatting in languages such as Java or C.

You can create and edit message classes by using transaction SE91.

To read more about Messages and Message classes, click here.

Read more...

Exception Classes

For all you C++, Java and .NET developers, the concept of exception classes, which is relatively new in ABAP, will be easy to understand.

Exception classes are, as their name imply, classes that define exceptions.
Exception classes are created in a manner similar to creating regular ABAP classes. You can create exception classes in SE80, but you choose “Exception class” as the class type.

Java developers are probably familiar with the concept of checked exceptions and unchecked exceptions. ABAP has this concept as well. As the ABAP documentation explains:

• “If exceptions defined via subclasses of CX_STATIC_CHECK are propagated from a procedure, they must be explicitly declared in the interface of the procedure. The syntax check makes a static check of whether all exceptions triggered in the procedure with RAISE EXCEPTION or declared in the interfaces of the calling procedures are either handled with CATCH or explicitly declared in the interface and issues a warning if this is not the case.”

• “If exceptions defined via subclasses of CX_DYNAMIC_CHECK are propagated from a procedure, they must be explicitly declared in the interface of the procedure. However, this is not checked statically by the syntax check; instead, it is checked dynamically at the point in time when such an exception is propagated from a procedure.”

• “Exceptions that are defined via subclasses of CX_NO_CHECK may not be explicitly declared in the interface of the procedure. The CX_NO_CHECK class and its subclasses are always implicitly declared and are always propagated, whereby resumability is retained if it exists.”

You can therefore see the first type is like checked exceptions, the second and third types have some similarities to unchecked exceptions.

You can find more about ABAP Exception Categories here. You can find more about ABAP exceptions in general here.

SAP SDN also has a good article explaining the difference between the old exception using method and the new one. You can access it here, but you need to have an SDN account in order to read it.

Read more...

Lock Objects

Lock objects are used to manage database locking in your program. Locking is important in case you expect concurrent accesses to a database table.

You create lock objects in either SE11 or SE80 transactions (under the Dictionary Object in the navigation tree)

Each lock object you create is associated with a database table. You can choose by which fields in the table you lock. For example, in case you have an Employee table, you can choose to lock the table by the ID field of the table. After the creation of a locking object, two methods are available for your use – ENQUEUE_objectname and DEQUEUE_objectname, where objectname is the name of the lock object you created. The former allow you to lock an entry in the table, the latter releases the lock object.

There are many types of locks and we’ll not discuss them here. SAP’s official guide on locks can be found in the SAP Help. A nice step by step tutorial on locking objects can be found in Richard Sanots’ blog.

Read more...

Ten ABAP Transaction You Will Probably Use Most

SE80 – Object Navigator
SE80 is the most important transaction for the ABAP programmer. It’s the entry point for the workbench. From SE80 you can for example create new packages, classes, programs, dictionary objects (database tables) etc.

SE11 – Dictionary
Using SE11, you can create and maintain database objects such as Database tables, data types, and lock objects.

SE30 – Performance
SE30 is used for testing performance. Want to compare two bits of code that do the same thing and see which one runs quicker? SE30 is the place to do it.

SECATT – Extended Computer Aided Test Tool
Extended Computer Aided Test Tool (or ECATT) is a built-in tool to test SAP system. By using eCATT you can:
• Test transactions, reports, and scenarios
• Call BAPIs and function modules
• Test remote systems
• Check authorizations (user profiles)
• Test updates (database, applications, GUI)
• Test the effect of changes to customizing settings
• Check system messages

SU01 – User Maintenance
This is the place to maintain user data such as personal data, roles, logon data (passwords) etc. It’s kind of like SAP’s Java WAS’s User Management Engine (UME).

SE81 –Application Hierarchy
SE80’s less famous sister, SE81 allows you to browse SAP applications. Clicking on a node (application) on SE81 opens that application in SE80.

SE91 –Message Classes
SE91 allows creating and maintaining message classes.


SM12 –Lock Entries

Using this transaction you can see which lock objects are used by which user for a table of your desired. See the postregarding lock entries for more information...

SM30 – Maintain Table Views
Using this transaction you can maintain table views, manually adding, editing and removing information from existing tables for which you created a table view.

For a more extended list of frequently used ABAP Transactions, visit the list of ABAP transaction codes, courtesy of SAPTechies.com

Read more...

How I came to meet ABAP

I’ve been working as a software developer for 5 years now. During my career as a software developer, I had experience with many programming languages. I started as a C/C++ programmer(*), continued to Java and J2EE, and even had some experience with C#.
One day, not long ago, my manager announced that our project would require some programming in ABAP. He asked me to be one of the first developers that would make the transition to ABAP.
I was not overjoyed by the request, to say the least. ABAP seemed to me like an archaic programming language, a creature of the 80’s with an uncertain future. I had some experience with SAP systems written in ABAP, and I knew that almost all of SAP’s applications and systems were written in ABAP, but that’s pretty much everything I knew about the language. So I started to read more about ABAP.

Here are two surprising facts that I came to learn about ABAP:

1. The TIOBE Programming community index, in July 2009 ABAP was ranked in the 16th place in terms of popularity(**). Just for comparison, Java is ranked first, C# is ranked 6th, Pascal is ranked 15th, and Cobol is ranked 24th.
2. ABAP is an Object Oriented Language. To be more precise, ABAP has an extension which supports object oriented programming. Much like with C++, you can still write a mixture of procedural code and object-oriented code in ABAP. The concept of OO in ABAP is fairly new. It was introduced in 1999, along with R/3 release 4.6.

Anyway, I began programming in ABAP, and naturally I started to encounter some problems. I also bumped into some interesting material. As I do whenever I study a new subject, I kept some notes solutions to the problems I encountered and summaries of the topics I studied. Then I thought, why not turn these notes into a blog? If they could be useful to me, they would be useful to anyone starting to learn ABAP.
So here it is, my blog about ABAP. I invite you to join me on my journey exploring ABAP. I’ll try to share as many tips for the beginning ABAP developer as I can, and hopefully, with time, it’ll also contain some advanced topics.

(*) Yes, I know some people would be shocked from the fact that I’m even mentioning the two languages in the same sentence. But yes, there are some products out there that were written in a mixture of procedural C and Object Oriented C++. I got to work on one of them. Deal with it.

(**)
According to TIOBE, “the ratings are based on the number of skilled engineers world-wide, courses and third party vendors. The popular search engines Google, MSN, Yahoo!, Wikipedia and YouTube are used to calculate the ratings. Observe that the TIOBE index is not about the best programming language or the language in which most lines of code have been written.”

Read more...

About

This blog contains tips, tricks, tutorials, and stories about my personal experiences with the SAP ABAP language.

About the Author
Yours Truly has been a developer for more than 5 years now, with experience with C, C++, Java/J2EE, and, recently, with ABAP.

Read more...

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP