Saturday, 4 August 2012

Division by Zero in ABAP

ABAP has a strange behaviour when division by zero is considered.

Mathematically: Division by zero is undefined. Also all the other programming languages raise an exception when a number is divided by 0.

However ABAP has a strange an unexpected behavior in this regard.

ABAP raises an exception CX_SY_ZERODIVIDE  when any number is divided by 0 but not when the dividend is also 0.

Example:

CASE I
data :  dividend type i value 10.
data :  divisor   type i value 0.
data :  answer type i.

answer = dividend / divisor.  ->> Raises an exception CX_SY_ZERODIVIDE.

 CASE II
data :  dividend type i value 0.
data :  divisor   type i value 0.
data :  answer type i.

answer = dividend / divisor.  ->> No exception raised

answer  will contain 0 as a result.

This is an arbitrary behaviour of ABAP and coders should take care to handle this situation in their code.

The runtime error associated with the zero divide exception is BCD_ZERODIVIDE.



Sunday, 29 July 2012

Using Perform in a SAP Script

The purpose of this post is to demonstrate how to call a subroutine from an SAP Script.

There might be a requirement where you may have to call a form from within the window of a SAP Script.It can be used for formatting of the output or performing some calculations.

Example : We will call a subroutine from the script to format the output. Suppose the variable coming from the print program contains a date and the requirement is to insert a blank space between each digit.

IN SCRIPT:

We use a DEFINE statement in SAP Script to declare local variables. These are of character type by default.

/* define a local variable variable2 in sap script to hold value of zdate coming from print program.
/: DEFINE &VARIABLE2& := &ZDATE&.
/* call the subroutine in report ztest
/: SET DATE MASK = 'DDMMYYYY'
/: PERFORM CHANGE_FORMAT IN PROGRAM ZTEST
/: USING &ZDATE&
/: CHANGING &VARIABLE2&
/: ENDPERFORM
/* display the  changed value
* &VARIABLE2&


IN PROGRAM:

The form definition can be given in any report and not necessarily in print program.

DATA  : LD TYPE C LENGTH 15.

FORM CHANGE_FORMAT TABLES L_DATA_IN STRUCTURE ITCSY L_DATA_OUT STRUCTURE ITCSY.
CLEAR : LD.
READ TABLE L_DATA_IN INDEX 1.
MOVE L_DATA_IN-VALUE TO LD.

CONCATENATE  LD+0(1)
                               LD+1(1)
                               LD+2(1)
                               LD+3(1)
                               LD+4(1)
                               LD+5(1)
                               LD+6(1)
                               LD+7(1)
INTO LD SEPARATED BY SPACE.

READ TABLE L_DATA_OUT INDEX 1.
MOVE LD TO L_DATA_OUT-VALUE.
MODIFY L_DATA_OUT INDEX 1.

ENDFORM.


RESULT:

INPUT VALUE IN ZDATE : 29072012

OUTPUT VALUE IN VARIABLE2 : 2 9 0 7 2 0 1 2