Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
Recent
Topics
Tutorials
NEXT
PREV
Highlights
Chapter 5: WRITE Statement (Classical
Reporting)
CHAPTER4
Settings
Feedback
ABAPLanguageBasics
Sign Out
Introduction
AdvancedBusinessApplicationProgramming(ABAP),theproprietary
languageofSAP,hasbasicallyprocedureorientedconstructs.Whenit
wascreated(inthe1970s),therewasnoOOPtechnologyapplication.The
OOPconstructsinABAPwereincorporatedsometimeinthebeginningof
themillennia.Itisaninterpreterdrivenlanguage.Anditslimited
Settings
10 days left in your trial. Subscribe.
Feedback
repertoireofstatementsandfeaturesatthetimeSAPR/3release(in
1992)havegrownconsiderably.
Sign Out
TheABAPsourceprogramsarestoredintheSAPdatabase.Thecomplied
runtimeversion,muchakintotheJavabytecode,isalsostoredinthe
SAPdatabase.ThemaintenanceofABAPsourceprogramscanbedone
onlyintheSAPenvironment:thatis,youhavetobeloggedintoSAPto
create,edit,andsyntaxcheckABAPprograms.
TheABAPprogramscanonlybeexecutedintheSAPenvironment.The
executionofABAPrequirestheABAPruntimeenvironment,only
availablewhenyouareloggedintoSAP.AnABAPruntimecodeis
extractedfromthedatabase,loadedontotheRAMofanapplication
server,andexecutesintheapplicationserverandpresentationserver
forinteractionwiththeenduser.
Enjoy Safari? Subscribe Today
TheABAPruntimeenvironmentispartoftheworkprocesses,andthe
workprocessesare,inturn,componentsoftheapplicationserver,which
iscalledtheNetWeaverApplicationServer(AS)ABAP.TheNetWeaver
ASABAPhasthecompletetechnologyandinfrastructuretorunABAP
applications.
Theworkprocesses(componentsofNetWeaverASABAP)execute
individualdialogstepsofABAPapplicationprograms.Thework
processesareconstitutedbytheABAPprocessor,thescreenprocessor,
andthedatabaseinterface.TheABAPprocessortakescareofthe
processinglogicofABAPprograms,andthescreenprocessortakescare
ofthescreenflowlogicandthedatabaseinterfacetoprovideallthe
databaserelatedservices(DDICispartofthisdatabaseinterface).
AlmosttheentireSAPERPapplicationhasbeendevelopedinABAP.
EveryscreenintheSAPenvironmentisanABAPprogram.Ifyouclick
onthebutton
ontherightsideofthestatusbar,yougetABAP
programinformation.TheSE11transactionoperationsyouperformedin
thelasttwochaptersarecodedinABAP.
TheABAPlanguageisusedbyABAPimplementationconsultantsto
customizeinterfacesandreportsandtoperformenhancementsofSAP
providedfunctionalities.
Inthischapter,theABAPlanguagebasicelementsarecovered:data
typesavailable,datadeclarativestatements,arithmeticoperations,
stringhandling,datamovement,conditiontesting,andrepetitive
processlooping.Theseelementsarepartofallcomputerlanguages.
Mostofyouarealreadyfamiliarwiththese.Youwilllearnhowthese
elements,whicharecommontoallcomputerlanguages,existand
operateinABAP.
ForadetailedtheoreticaltreatmentofABAPprogramming,youcanrefer
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
1/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
fromtimetotimetothedocumentABAPProgramming(BCABA),
downloadablefromthelinkgivenintheintroductiontothebook.
ABAPDataTypes
InChapter2,youwereintroducedtotheDDICdatatypes.Shownin
Figure41arethedatatypesavailableinABAPprogramscalledtheABAP
types.
Figure41.DatatypesinanABAPProgram
ElementaryTypes
Inelementarytypes,theFixedLength(typesC,D,N,T,F,I,P,andX)
meansthateitherthelengthofthistypeisinherentlyfixed(TYPESD,F,
I,orT)orwhiledeclaringadataitemlengthinbytesorcharactersis
specifiedforthatdataitem,andthelengthofthisdataitemremainsfixed
allthroughitsexistence.
InVariableLength,(typesSTRINGandXSTRING),thelengthofadata
itemisnotspecifiedwhiledeclaringit:itvariesduringtheexecutionofa
programasyouassigndatatoit.
ThebunchingofelementarytypesasCharactertypesisforthetypesthat
storeoneASCIIcharacter/byte(ina16bitUnicodesystem,2
bytes/character).ThebunchingasNumerictypesisforthetypeson
whichyoucanperformnormalarithmeticoperations.Youcanperform
arithmeticoperationsonelementarytypeN,butitisnotveryadvisable.
YoucanperformdatearithmeticonelementarytypeDandtime
arithmeticonelementarytypeT.
Table41describestheelementarydatatypesthatarepredefinedin
ABAP.(Thevalidsizeandinitialsizearegiveninbytesorcharacters.)
ThemappingtoDDICdatatypesisalsospecified.
Table41.ABAPElementaryDataTypes
ThedatatypesD,F,I,andTarepredefinedinallrespectsincludingthe
size,butthedataTYPESC,N,P,andXcanhaveadditional
specifications.Forexample,youcanspecifythesizeofthesedatatypesin
theprograminbytesorcharacters,whendataisdeclared.FortypeFand
P,youcanspecifythenumberofdecimalswiththedatadeclaration.
TheInitialSizecolumnspecifiesthedefaultlength,adataitemwill
assume,ifitslengthisnotspecifiedwhiledeclaringadataitem.
ComplexTypes
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
2/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
Thecomplextypesarecategorizedintothe(a)structuretypesand(b)table
types.
1. Inthestructuretypes,elementarytypes,structuretypes(structure
embeddedinastructure)aregroupedtogether.Youwillconsider
onlythegroupingofelementarytypes.Thegroupinginvolving
structures(structure/sembeddedinaStructurenestedstructures)
areanadvancedfeaturebeyondthescopeofthisbook.Youmustbe
awareofthefacilityoravailabilityofnestingofstructures.When
theelementarytypesaregroupedtogether,thedataitemcanbe
accessedasagroupeddataitemortheindividualelementarytype
dataitems(fieldsofthestructure)canbeaccessed.
2. Thetabletypesarecalledarraysinotherprogramminglanguages.
Arrayscaneitherbesimpleorstructurearrays.Thearraysare
calledinternaltablesinABAP.InABAP,theinternaltablescanbe
declaredandoperateduponinmanymorewaysthaninother
programminglanguages.Anentirechapter,Chapter6,entitled
InternalTablesisdevotedtothedeclarationsandoperationsof
internaltables.
ReferenceTypes(DiscussionIsinOOPContext)
Thereferencetypesareusedtorefertoinstancesofclasses,interfaces,
andruntimedataitems.
TheABAPOOPRunTimeTypeServices(RTTS)enablesdeclarationof
dataitemsatruntime.Areferencevariableoftype\\DataReference\\\
isusedtorefertoinstancesoftheruntimedataitems.
Whenaninstanceofaclassiscreated,areferencevariableoftypeClass
Referenceisused.
Whenaninstanceofaninterfaceiscreated,areferencevariableoftype
InterfaceReferenceisused.
Eitherofthereferencevariables,ClassReferenceorInterface
Reference,willbecategorizedasObjectReference.
ThediscussionofOOPcontextisover!
DataObjectsinABAPPrograms
InanABAPprogram,youcanworkwithfourkindsofdataobjects:
InternalDataObjects
InternaldataobjectsaredeclaredinaparticularABAPprogram.Theydo
nothaveanyexistenceoutsidetheparticularprogram.Internaldata
objectsareassignedRAM.Internaldataobjectsfurthercategorization:
Literals(constantsdefinedaspartofanABAPstatementor
command)
Variables
Constants
ExternalDataObjects
ExternaldataobjectsexistindependentofABAPprograms.Youcannot
workwiththemdirectly,butyoucancopythemtointernaldataobjects
andwritethembackwhenyouhavefinished.Externaldataobjectscan
beusedgloballythroughoutthesystemenvironment.
ABAPstoresexternaldataobjectsintablesdefinedintheDDIC.To
accessthisdatafromwithinaprogram,youdeclarethetablesinthe
programwiththeTABLESorDATAstatement.
SystemdefinedDataObjects
Besidesuserdefineddataobjects,somedataobjectsaredefined
automaticallybythesystem.Someofthesystemdefineddataobjects
SPACE,SYSUBRC,SYDATUM,SYUZEITandSYTCODE.
SpecialDataObjects
ABAPalsoincludessomedataobjectswithspecialfeatures,namely:
PARAMETERS
PARAMETERSarevariablesthatarelinkedtoaselectionscreen.They
canacceptvaluesafteranABAPprogramisstarted(input).
SelectioncriteriaSELECTOPTIONS
Selectioncriteriaarespecialinternaltablesusedtospecifyvalueranges.
Theyarealsolinkedtoaselectionscreen.Setofvaluesareacceptedafter
aprogramisstarted(rangesofvaluesinput).
Alldataobjectsyouwanttoworkwithintheprograms(exceptsystem
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
3/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
dataobjectsandliteraldataobjects)havetobedeclared.Whiledeclaring
dataobjects,youmustassignattributestothem.Themostimportantof
theseattributesisthedatatype(exceptfordataobjectdeclaredwith
keywordTABLE).InABAP,youcaneitherusepredefineddatatypes
similartootherprogramminglanguages,oruserdefineddatatypes.
TheuserdefineddatatypesinABAPprovideyouwithapowerfultool
sincetheyallowforgreatflexibilityinprogramming.Theyrangefrom
elementarytypes(e.g.,characterstringsofagivenlength)tovery
complexstructures(e.g.,nestedstructures).
Assigninguserdefineddatatypestodataobjectsallowyoutoworkwith
preciselythedataobjectsyourequire.Userdefineddatatypescanbe
usedinthesamewayaspredefineddatatypes.Youcandeclarethem
locallywithinaprogramorstorethemgloballyintheABAPDictionary
(DDICobject:TypeGroup).
Therearethreehierarchicallevelsofdatatypesandobjects:
Programindependentdata,definedintheABAPDictionary
Internaldatausedgloballyinoneprogram
Datausedlocallyinaprocedure(subroutine,functionmodule)
ABAPProgramComponents
ABAPprogramsaremaintainedwithtransactioncodeSE38.
AnABAPprogramconsistsoffivesubobjects(seeSE38screenradio
buttons):
1. Sourcecode(sourcelines)
2. Variants(willbecoveredinChapter9entitledSELECTION
SCREENandrequireknowledgeofInternalTablesand
SELECTIONSCREEN
3. Attributes(mandatory:Title,Type,(programtype)andPackage
(localobject/$TMP)
4. Documentation(Youwillnotcreateseparatedocumentationinthe
courseofyourexercises.Youwillcommentyourprogramsource
linesprofusely,makingthemselfdocumentaryaswellasself
explanatory)
5. Textelements,which,inturn,consistof:(i)TextSymbols,(ii)
SelectionTexts(willbecoveredinChapter9),and(iii)List
Headers(willbecoveredinChapter5)
Theattributes(item3)ofanABAPprogramconsistsof:
Title,equivalentofshortdescriptionyouwereenteringwhen
creatingDDICobjects
Originallanguage,loggedinlanguagecodewhentheprogram
wascreated(maintainedbythesystem)
Created,dateofprogramcreation,userid.(maintainedbythe
system)
Lastchangedby,lastdateofchange,userid.(maintainedbythe
system)
ProgramAttributesarea
Type:programtypeismandatory.Adropdownlistis
availablewiththefollowingoptions:
ExecutableprogramAprogramthatcanbeexecuted.
IncludeProgramThelinesoftheseprogramscanbe
incorporatedinotherprograms.
ModulePoolItcontainsscreenflowlogicmodules.
FunctiongroupItcontainsfunctionmodules,which
aregenericroutines.CannotbecreatedintheABAP
editor.(SE38)IstobecreatedinSE37,SE80.
SubroutinePoolItcontainsexternalsubroutines.
InterfacepoolItcontainsinterfaces.Cannotbe
createdintheABAPeditor.(SE38)Istobecreatedin
SE24.
ClasspoolItcontainsclasses.Cannotbecreatedin
theABAPeditor.(SE38)IstobecreatedinSE24.
TypePoolItcontainsuserdefinedTYPES.Cannot
becreatedintheABAPeditor.(SE38)Istobecreated
inSE11.
XSLTProgram.CannotbecreatedintheABAPeditor.
(SE38)IstobecreatedinSE80.
Status:Thisisanoptionalprogramcategorization.Adrop
downlistisavailablewiththefollowingoptions:
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
4/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
SAPStandardProductionProgram
CustomerProductionProgram
SystemProgram
TestProgram
Application:Anoptionalentry.Youcanassignaprogramto
anapplication.Adropdownlistisavailable.
AuthorizationGroup:Anoptionalentry.Authorizationisa
securityfeature.Apopup(F4)listisavailable.
Package:AnyobjectcreatedintheABAPWorkbench
environmentistobeassignedapackage.Youare
designatingallyourobjectsaslocal(i.e.,nottransportableto
otherimplementationenvironments).Youareassigningthe
SAPdeliveredpackage$TMP.
Logicaldatabase:Anoptionalentry.Logicaldatabaseis
basicallyadataretrievalreusableobject.ALogicaldatabase
createdcanbeusedbymultipleprograms(programsthatare
retrievingsimilardatafromalmostthesamedatabase
tables),savingtheeffortofdataretrievalintheprograms
usingtheLogicaldatabase.Worksslow.StillusedintheHR
Module.
Selectionscreen:Anoptionalentry.Maintainedbythe
systemorgoesalongwiththeLogicaldatabase.Willbe
coveredinChapter9entitledSELECTIONSCREEN.
Editorlockcheckbox:Enablingthispreventsotheruserids
fromeditingtheprogram.
Fixedpointarithmeticcheckbox:Enabledbydefault.In
businessapplications,youperformmostlyfixedpoint
arithmetic,notfloatingpointarithmetic.
Unicodechecksactivecheckbox:Toenabletheprogram
syntaxchecksrelatingtoUnicode.
Startusingvariantcheckbox:WillbecoveredinChapter9
entitledSELECTIONSCREEN.
AscreenshotofABAPprogramattributesisshowninFigure42.
Figure42.ABAPProgramAttributes
ABAPEditors
TherearethreetypesofABAPeditorsyoucanchoosefrom:(i)FrontEnd
Editor(New),(ii)FrontEndEditor(Old),or(iii)BackEndEditor.To
chooseanABAPeditor,ontheSE38ABAPEditor:InitialScreen,select
themenuoption:Utilities(M)
Settings...Thismenuselectionpops
upthescreenasshowninFigure43.
Figure43.ABAPEditorUserSpecificSettings
FrontEndEditor(New,alsoCalledSourceCodeMode)
ItismostrecentfromtheABAPeditors,SourcecodemodeSourcecode
modeandasitsnamesuggests,theeditorprogramisloadedin
presentationserver.Theprogramlinenumbersappearkeywords
appearinaseparatecolor,whenthefirstfewlettersofkeywordare
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
5/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
enteredandthesystemproposesthekeyword.Evenasyouenter
programlines,theeditorinteracts.Ithasahostofformattingfacilities.
Youcanselectfont,etc.specificallyforeditorenvironmentseparate
fromSAPenvironment.Itshouldbethepreferredchoiceforthose
startingtolearnABAPprogramming.
FrontEndEditor(Old,alsoCalledPlainTextMode)
ItisthepredecessorofPlaintextmodePlaintextmodethenewfrontend
editor.Theeditorprogramisloadedinpresentationserver.Theprogram
linenumbersdonotappear.Itisasimpletexteditorthereisnoaction
bytheeditorwhenyouenterprogramlines(i.e.,nointeractiveness).
BackEndEditor(alsoCalledLineBasedMode)
Thisismorelikealineeditorthanatexteditor.Selectingmultiplesource
linesinvolvesextraeffort.Youhavetheoptiontomakeprogramline
numbersappearanddisappear.Itisrecommendedtobeusedwhen
handlinglargeprogramsinawideaccessnetwork.LinebasedmodeLine
basedmode
ThethreemodesoftheABAPeditorareinterchangeableandcompletely
compatible.
ThisisbareoutlineoverviewofthethreeABAPeditormodesthatis
ampletogetyoustarted.
CommonFeaturesoftheThreeABAPEditorModes
TheABAPsourceiscaseinsensitive:youcancodeinupperorlowercase.
Theconventionistouseuppercase.Inyourhandsonsourceprograms,
youarecodingthestatementsinuppercaseandusinglowercasefor
commentswithkeywordsincommentsintheuppercase.
Theusualtexteditorfeatures:navigation,selection,copy,cut,paste,
delete,undo,redo,save,etc.areimplicit.Theyarenotlistedhere.The
featureslistedhereareforabeginnerandnonadvancedABAP
programmer.
TheABAPeditoroffersthefollowingprimefunctionsandfeatures:
Table42.ABAPEditorPrimeFeatures
Feature
Menu
Path/Keys/Button
PrettyPrinterStandardizationof
Programlayout
Edit
Pretty
Printer
<Shift>+<F1>
PrettyPrinter
Button
PatternToautogeneratecodelines,
especiallywhencallingafunction
module,amethod.
Edit
Pattern
<Ctrl>+<F6>
PatternButton
Find,Findandreplacetext
Edit
Find/Replace
<Ctrl>+F
Button
Block/BufferX,Y,Z
InadditiontoO.S.clipboard,ABAP
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
6/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
editorofferseveryloggedinuserthree
otherbuffersdesignatedasX,Y,Z.
Thesearenonvolatilebuffers.Their
contentsaresavedintheSAPdatabase
whentheuserlogsoff/serverisshut
Utilities(M)
Block/Buffer
downandrestoredwhenuserlogsin
again.Thesebufferscontentscanbe
editedaswell.
Upload/DownloadYoucanuploadtext
filesonthepresentationserverinto
yourABAPprogramsanddownloadyour
ABAPsourcelinesontoatextfileona
Utilities(M)
presentationserver
MoreUtilities
Upload/Download
Comment/DecommentSelectedBlock
<Ctrl>+<to
ofSourceLines.Ifyouwanttoconverta
comment
blockoflinesintocommentlinesorvice
versa,usethisfunction.InABAPaline
<Ctrl>+>tode
withasterisk(*)inthefirstcolumnis
comment
treatedasacomment.
CheckProgramSyntax
Program
Check
Syntax
<Ctrl>+<F2>/
button
ExtendedProgramCheck
Program
Check
ExtendedProgram
Check
CodeInspector
Program
Check
CodeInspector
ActivateProgram
Program
Activate
<Ctrl>+<F3>/
button
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
7/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
Test/Run/ExecuteProgram
Program
Test
DirectProcessing
<F8>/
Button
TogglebetweenEdit/ChangeMode&
DisplayMode
Program
Display
Change
<Ctrl>+<F1>
button
Youcanusethecontextmenu(mouserightclick)aswellformostofthese
operations.
Thereisalsoaverysophisticateddebugger,aruntimeanalysisfacility
andanonlinehelp(ABAPdocumentation)availableintheABAP
developmentalenvironment.
ABAPProgramStructure
AnABAPprogramconsistsofthefollowingtwoparts:
DeclarationPartGlobalData,SelectionScreens,andLocalClasses
Allglobaldatadeclarationstatements(globalinthecontextofa
program).Globaldataisaccessibleinallinternalprocessing
blocks.Youdefineitusingdeclarativestatementsthatappear
beforethefirstprocessingblock,indialogmodules,orinevent
blocks.Youcannotdeclarelocaldataindialogmodulesorevent
blocks.
Allselectionscreendefinitions.
Alllocalclassdefinitions(CLASSDEFINITIONstatement).
Datadeclarationstatementsmadeinprocedures(methods,
subroutines,functionmodules)formthedeclarationpartforlocal
datainthoseprocessingblocks.Thisdataisonlyexistent,
accessibleintheprocedureinwhichitisdeclared.
ContainerforProcessingBlocks
ThesecondpartofanABAPprogramcontainsalloftheprocessingblocks
fortheprogram.Thefollowingtypesofprocessingblocksexist:
Dialogmodules(nolocaldataarea,whateverdatadeclaredtreated
asglobal)
Eventblocks(nolocaldataarea,whateverdatadeclaredtreatedas
global)
Procedures(methods,subroutines,andfunctionmoduleswiththeir
ownlocaldatadefinitions)
ThedialogmodulesandproceduresareenclosedintheABAPkeywords
thatdefinethem.Therearekeywordsforstartofmodules,procedures
andcorrespondingkeywordsforendofmodulesandprocedures.Event
blocksareintroducedwitheventkeywordsandconcludeimplicitlywith
thebeginningofthenextprocessingblock.
AllABAPstatements(exceptdeclarativestatementsinthedeclaration
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
8/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
partoftheprogram)arepartofaprocessingblock.NondeclarativeABAP
statements,whichoccurbetweenthedeclarationofglobaldataanda
processingblockisautomaticallyassignedtotheSTARTOFSELECTION
eventorprocessingblockbytheABAPprocessor.
CallingProcessingBlocks
YoucancallprocessingblockseitherfromoutsidetheABAPprogramor
usingABAPstatementsthatformpartofaprocessingblock.Dialog
modulesandeventblocksarecalledfromoutsidetheABAPprogramby
theABAPruntimeenvironment.ProceduresarecalledusingABAP
statementsinABAPprograms.
Callingeventblocksisdifferentfromcallingotherprocessingblocksfor
thefollowingreasons:
Aneventblockcallistriggeredbyanevent.Useractionsonselection
screens,lists,andtheruntimeenvironmenttriggereventsthatcanbe
processedinABAPprograms.Youonlyhavetodefineeventblocksfor
theeventstowhichyouwanttheprogramtoreact(whereasasubroutine
call,forexample,musthaveacorrespondingsubroutine).Thisensures
thatwhileanABAPprogrammayreacttoaparticularevent,itisnot
mandatorytodoso.
ABAPStatementStructure
AnABAPsourceprogramwillconsistofcommentsandABAPstatements.
Comments
Acommentcanbeincorporatedby
1. Startingalinewithanasterisk(*).Theasteriskhastobeinthe
veryfirstcolumnoftheline.Anasteriskinthefirstcolumnwill
maketheentirelinecomment.Like:
*ThisistheHelloWorldprogram
2. Byusingadoublequote(").Whateverfollowsthedoublequoteis
treatedascomment.Thisisarightsidecommentyoucan
incorporatecommentsontherightsideofanABAPstatement.Ifa
linestartswithadoublequote,theentirelineistreatedas
comment.AlinecouldhaveanABAPstatementfollowedbya
comment.Like:
WRITE/'HelloWorld'."thiswilloutputthestringliteralHelloWorld
Youcanalwayshaveblanklinesinthesourcecode.
ABAPStatements
ABAPstatementsbeginwithanABAPkeywordandareterminatedbya
period(.)oracomma(,)whentheyarewithinachainandnotthelast
statementinthechain.Thelaststatementinachainmustterminatewith
aperiod.ABAPstatementscanrunintomultiplelinesoralinemay
containmultipleABAPstatements.Enterpriseconventionisnottocode
lineswithmultipleABAPstatements.
Astatementrunningintomultiplelines:
DATACOMPANY_NAME(50)TYPECVALUE
'NOBIGDEALInc.'.
Alinewithmultiplestatements:(twostatements)
DATAEMPLOYEE_CODE(5)TYPEN.DATAEMPLOYEE_NAME(25)TYPEC.
InthislastlineofABAPcode,thekeywordDATAisrepeated.The
keywordDATAisusedtodeclarevariables(onetypeofinternaldata
objects)inanABAPprogram.Arealworldprogramwouldhavemany
variablesdeclaredeachofthesedeclarationsmuststartwiththekeyword
DATA.TheABAPeditorprovidesameanstoavoidtherepetitionof
word/sthroughthefeatureofchainingstatements.
Inthechainingfeature,whateverwordorwordsrepeatingontheleft
sideofABAPstatementswillbechainedandtherepetitionisavoided.
Theabovecoderewrittenwithchainingwillbe:
DATA:EMPLOYEE_CODE(5)TYPEN,EMPLOYEE_NAME(25)TYPEC.
ThekeywordDATAisfollowedbyacolon(:)tosignifychaining.Thefirst
statementisnotterminatedbyaperiodbutbyacommaandthelast
statementinthechainisterminatedbyaperiod.Anotherexampleof
chaining:
WRITE/5:'FIRST','SECOND','THIRD','FOURTH'.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
9/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
Unchainedversionofthis:
WRITE/5'FIRST'.WRITE/5'SECOND'.WRITE/5'THIRD'.WRITE/5FOURTH'.
ABAPStatementsandKeywords
ThefirstelementofanABAPstatementisanABAPkeyword.The
keyworddeterminesthecategoryofthestatements.Thedifferent
statementcategoriesare:
DeclarativeStatements
Thesestatementsdeclareuserdefineddatatypesordeclareinternal
dataobjectsthatareusedbytheotherstatementsinaprogramor
routine.
Examplesofdeclarativekeywords:
TYPES,DATA,TABLES
ModularizationStatements
ThemodularizationstatementsdefinetheprocessingblocksinanABAP
program.
Themodularizationkeywordsarefurthercategorizedinto:
EventKeywords
Youuseeventkeywordsinstatementstodefineeventblocks.Thereare
nostatementstosignifytheconclusionofprocessingblockstheyend
whenanotherprocessingblockisdefined.
Examplesofeventkeywords:
INITIALIZATION,ATSELECTIONSCREEN,STARTOFSELECTION,END_OF_SELECTION
Definingkeywords
Youusestatementscontainingthesekeywordstodefinesubroutines,
functionmodules,dialogmodules,andmethods.Youconcludethese
processingblocksusingthecorrespondingENDstatement.
Examplesofdefinitivekeywords:
FORM.....ENDFORM.
FUNCTION...ENDFUNCTION.
MODULE....ENDMODULE.
ControlStatements
YouusethecontrolstatementstocontroltheABAPprogramflowwithina
processingblockaccordingtoconditions.
Examplesofcontrolkeywords:
IF...ENDIF,WHILE...ENDWHILE,CASE...ENDCASE.
CallStatements
Youusethecallstatementstocallprocessingblocksthatyouhavealready
definedusingmodularizationstatements.Theblocksyoucallmaybe
locatedinthesameoradifferentABAPprogram.
Examplesofcallkeywords:
PERFORM,CALL,MODULE
OperationalStatements
Thekeywordsoperateonthedatathatyouhavedefinedwithdeclarative
statements.
Examplesofoperationalkeywords:
WRITE
MOVE
CONCATENATE
DatabaseStatements
ThestatementsusethedatabaseinterfacetoaccessthetablesintheSAP
databasesystem.Examplesofdatabasekeywordsare:
SELECTandINSERT
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
10/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
Now,thatyouhavehadareviewofABAPprogramcomponents,ABAP
editor,ABAPprogramstructure,andABAPstatementstructure,youare
readytocodeyourfirstprogram.
FirstABAPProgram
YouwillcreatetheproverbialHelloWorldprogram.Youwill,though,
createitwithamultilingualfacility.Youwillprogramitinawaythatthe
usercanseethetextisoutputintheloggedinlanguage,usingthe
multilanguagesupportfeatureofSAP.Andyouwillbeintroducedtothe
ABAPprogramfeaturethatwillenablethis:maintainmultilingualtexts.
YouwilluseaWRITEstatementtooutputthetext.TheWRITE
statementisbeingintroducedinapreviewmanner.TheWRITE
statementisformallyintroducedinchapter5entitledWRITEStatement
(ClassicalReporting).
OntheSE38screen,entertheprogramname
YCL_CH04_01_HELLO_WORLD.ThenamespaceofanABAPprogram
isamaximumof30charactersandmuststartwithlettersYorZ,butthe
restcanbealphanumericwithembeddedunderscores.(_)
ClickontheCreatebuttonorpressfunctionkeyF5.Theprogram
attributesscreenappears.Enterasuitableprogramtitle.Selectthe
Executableprogramintheprogramtype.Clickthesavebuttononthe
dialogbox.Thesystemwillpromptforapackage.Assignyourusual
package$TMP.ThesystemwillgeneratetheREPORTstatementand
enterintotheABAPeditormode.
IntheABAPprogramenvironment,youcancreateandmaintain
multilingualtextthroughtheTextSymbolssubcomponentofthe
programcomponentTextelements.TheTextelementsareattachedto
ABAPprogramsandcanbeaccessedfromwithinthatprogramonly.Of
courseTextelementscanbecopiedfromoneprogramtoanother
(TransactioncodeSE32).
YouwillcreateaTextSymboltocontaintheHelloWorldtext.TheText
Symbolscanbeassignedathreecharacteralphanumericidentification
andbereferredtobythatidentification.
TocreateTextSymbolsfromwithintheABAPeditor,selectthemenu
optionGoto
TextElements
TextSymbols.Thescreenwiththe
createdtextisshowninFigure44.
Figure44.MaintainingTextSymbolsInformationMessageon
Saving
Thedefinedlengthisthelengthoftheenteredstring.Themaximum
lengthbydefaultisthedefinedlength.Ifyouenteredtextinatext
symbolid.:forexample,001andwanttosubsequentlyaddmoretextto
it,youwillhavetomanuallyadjustthemaximumlengthtobeabletoadd
moretexttothetextsymbolid001.ThisisjustlikeitwasintheDDIC
dataelementlabelenvironment:notveryuserfriendly.
ManuallycreatetheGermanequivalenttextofHelloWorld.Todoso,
selectthemenuoptionGoto
Translate.Apromptwillappearfor
sourceandtargetlanguages.EnterENasthesourceandDEasthe
targetlanguages,thenclickonthecontinuebutton.Ascreenasshownin
Figure45appears.
Allthetextassociatedwithaprogramappearsonthisscreen.Inthe
presentcontext,youhaveonlytwotextitemsassociated:theprogram
titleandasingletextsymbol.
Figure45.TextSymbolsMaintainingLanguageTexts
TheGermanequivalentofHelloWorldHalloWalthasbeenmanually
entered.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
11/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
Thereisprocedureofautomatictranslationbythesystemtranslator.Itis
abitcomplexandadigressionforthescopeofthisbook.
Pressthesavebuttonandgobacktotextelementtextsymbolscreen
andactivatethetextsymbol.Activationofthetextsymbolisseparate
fromactivationoftheABAPsourceprogram.
ReturntotheABAPsourceeditorscreen.Yourprogramwilllooklike:
REPORTYCL_CH04_01_HELLO_WORLD.
***********************************
*HelloWorld!UseTextSymbol*
***********************************
WRITE/5TEXT001."/startoutputonnewline.5startoutput
"from5thcolumn.
"textsymbolsareaddressedwithprefixTEXT,
"followedbythetextsymbolthreecharacter
"identification
TheWRITEstatementoutputsdataobjectsonthescreen.Theoutputon
thescreencanbeprinted,spooled,etc.Theprogramcommentsexplain
thesyntaxoftheWRITEstatement.
Savetheprogram,performasyntaxcheck,andactivate.Executethe
program.TheoutputwillappearasinFigure46.
Figure46.HelloWorldoutputusingTextSymbols
LogintotheGermanlanguage.ExecutethisProgram.Theoutputwill
appearasinFigure47.
Figure47.HelloWorldoutputLoggedinGermanusingText
Symbols
Observethattheprogramtitleisnotappearingabovetheoutputofthe
WRITEstatement,evenasitisnotappearinginthewindowtitle.Thisis
becauseyouhavenotcreatedanyGermantextfortheprogramtitle.
ABAPProgramOutputaFewSystemFields
SystemFields
OneofthedataobjectsinanABAPprogramisthesystemdataobject.The
systemdataobjectconsistsofthesystemfieldsorvariables.Thereare
morethanonehundredsystemfields.Thesystemfieldsmakeavailable
totheABAPdeveloper,informationrelatedtotheABAPruntime
environment.Forinstance,therearesystemfieldsthatgiveloggedin
information:user,client,language.Thereisasystemfieldthatprovides
thedeveloperwiththesuccessorfailureinformationofanoperation.
YouwillfindacompletelistofthesystemfieldsinthePDFdocument
ABAPProgramming(BCABA)underSystemFields,downloadable
fromthelinkgivenintheIntroductionofthisbook.Thesystemfieldsare
listedalphabeticallyaswellasthemewiseinthismanual.
ThesystemfieldsstartwiththeprefixSY.Therearefivecategoriesof
thesesystemfields.Thecategoryofthesystemfieldisidentifiedbyicon
flagsasfollows:
Thiscategoryofsystemfieldsissetbytheruntimeenvironment.
Thedevelopercaninterrogatethefieldforitsvalue.
Thesearesetbytheruntimeenvironmentyoucanchangetheir
valueinaprogram.Itwillaffecttheruntimebehavioroftheprogram.
TheseshouldbesetintheABAPprogram.Theywillbeusedbythe
runtimeenvironmentandintheprogram
ForSAPinternaluse.
Obsolete.
Thesystemfieldswillbeintroducedasandwhentheircontextarises.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
12/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
YoushouldalsobeawareofthesystemfieldDDICDataTypeandlength.
Thisisavailableinthelist.YouwillfindthattheDataTypeandlengthof
theveryfirstsystemfieldSYABCDEisCHAR,26toaccommodatethe
26alphabetlettersoftheEnglishlanguage.
Thirteensystemfieldsareintroducedrightnow.Inthisprogram,you
outputthevaluesofthe13systemfieldslistedinTable43.
Table43.SystemFields
System
Description
Field
SY
EnglishAlphabetSet
ABCDE
SY
DateofApplicationServeronwhichtheProgramis
DATUM
Executing(YYYYMMDD)
SY
InstalledDatabase
DBSYS
SY
HostnameofApplicationServeronwhichthe
HOST
ProgramisExecuting
SY
Loggedinlanguage
LANGU
SY
Loggedinclient
MANDT
SY
ApplicationServerOperatingSystemonwhichthe
OPSYS
ProgramisExecuting
SY
NameoftheProgramwhichisExecuting/Current
REPID
Program
SY
NetWeaverVersion
SAPRL
SY
ApplicationServerSystemId.
SYSID
SY
CurrentTransactionCode
TCODE
SY
LoggedinUserName/Id.
UNAME
SY
TimeonApplicationServeronwhichtheProgram
UZEIT
isExecuting(HHMMSS)
Createthefollowingprogram,performasyntaxcheck,andactivate.
REPORTYCL_CH04_02_LIST_SYS_FIELDS.
**************************
*OutputSystemFields**
**************************
WRITE:/5'SYABCDE',SYABCDE,"/startoutputonnewline
/5'SYDATUM',SYDATUM,"5starttheoutputfrom5thcolumn
/5'SYDBSYS',SYDBSYS,":&,areforchainingi.e.avoiding
"repetitionofthekeywordWRITE
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
13/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
/5'SYHOST',SYHOST,"textliteralsenclosedinsinglequotes
/5'SYLANGU',SYLANGU,
/5'SYMANDT',SYMANDT,
/5'SYOPSYS',SYOPSYS,
/5'SYREPID',SYREPID,
/5'SYSAPRL',SYSAPRL,
/5'SYSYSID',SYSYSID,
/5'SYTCODE',SYTCODE,
/5'SYUNAME',SYUNAME,
/5'SYUZEIT',SYUZEIT.
Whenyouexecutethisprogram,thefollowingoutputisgenerated.
Figure48.OutputofProgram:
YCL_CH04_02_LIST_SYS_FIELDS
Intheprecedingcode,WRITEisthekeywordtooutput,and/istostart
theoutputonanewline:5tostartoutputfromcolumn5onwards.
ChaininghasbeenusedtoavoidrepetitionofthekeywordWRITE.
ForthefirstWRITEstatement,startingonanewline,fromcolumn5
onwards,theliteralSYABCDEanditsvalueareoutputonthesameline
onebesidetheotherwithablankcolumnbetweenthem.Similarlyforthe
succeedingWRITEstatements,atotalof13linesareoutput.
Youareusing13stringortextliterals(SYABCDEetal.)inthisprogram.
StringliteralsmustbeavoidedintheABAPprograms.Instead,enterthe
literalsinthetextsymbols(thatiswhattheyaremeantforwith
multilingualsupport).Butintheteaching,trainingparadigmthatyouare
in,thisprofuseuseofliteralsoccasionallycanbeexcused.
InternalDataObjects(Elementary)Declarations
Internaldataobjects(variables,constants,literals):
Dataobjectsarephysicalunitsthataprogramusesatruntime.
Eachdataobjecthasaspecificdatatypeassignedtoit.
Eachdataobjectoccupiessomespaceinmemory.
ABAPprocessesadataobjectaccordingtoitsdatatype.
Therearethreehierarchicallevelsofdatatypesandobjects:
1. Programindependentdata,definedintheABAPDictionary
2. Internaldatausedgloballyinoneprogram
3. Datausedlocallyinaprocedure(subroutine,functionmodule)
Variables
Avariableisusedtostoreandreferencedataunderacertainnameand
inacertainformat.Variablescandifferin:
name
type
length
structure
YoudeclarevariablesinyourprogramwiththeDATAstatement.
NamingaVariable(internaldataobjectsname,specialdataobjects
name)
Thevariablesandconstantsnamesofinternaldataobjectsmaybeupto
30characterslongandspecialdataobjectsup8characters.Youcanuse
anyalphanumericcharactersexcept:
Plussign+oraperiod.oracomma,oracolon:orparentheses()
Donotuseanameconsistingentirelyofnumericcharacters.
ABAPProgram:DeclareInternalDataObjectsVariables(withVALUE)
Output
Theprogramdeclareseachofthe10elementarytypesofdataobjectsand
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
14/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
assignsappropriate,applicablelengthsanddecimals.Itassignseachof
thesedataobjectsstartingvaluesthroughtheVALUEclause.(Except
XSTRING,whichdisallowsthis.)
TheprogramoutputsthevalueofthesedataobjectsthroughtheWRITE
statementalreadyintroduced.
Createtheprogram,performasyntaxcheck,andactivate.
REPORTYCL_CH04_03_ELEM_DATA_OBJECTS.
*******************************************************************
*declareelementaryDATAobjects,assignvalueswithdeclaration*
*outputdataobjects*
*******************************************************************
***********************************************************************
*keywordDATAusedtodeclaredata(variables)**
***
*:&,usedforchainingi.e.avoidrepetitionofkeywordDATA.**
***
*variableTYPEisspecifiedwiththekeywordTYPEfollowedby**
*C/D/F/I/N/P/T/X/STRING/XSTRING.ifTYPEnotspecified,assumes**
*defaultTYPEasC.**
***
*lengthtobespecifiedforTYPESC,N,P,Xinparenthesis.length**
*isinbytesforP&X.iflengthnotspecifiedforTYPESC,N,P,X**
*itassumesthedefaultlength.(seetable41)lengthsofTYPES**
*D,F,I,Tisfixed.TYPESSTRING,XSTRINGlengthvariesatruntime**
***
*theVALUEclauseistoassignastartingvalue.itisoptional.**
***
*decimalsforTYPEF,ParespecifiedwithkeywordDECIMALS**
*followedbythenumberofdecimals**
***
*ifsinglequoterequiredaspartofliteralstring,singlequote**
*shouldbeenteredtwicelike'ABC'''isforstringABC'**
***********************************************************************
DATA:CNAME(25)TYPEC
VALUE'MPHASISanH.P.Company',"lengthinparenthesis
"VALUEisoptional
TODAYTYPED
VALUE'20130101',"numericliteralsnotcontaininganysign
"&decimalcanbeenclosedinsinglequotes
"numericliteralscontainingsignordecimal
"shouldbeenclosedinsinglequotes
FNUMTYPEFVALUE'12345.6789',
COUNTTYPEIVALUE987654321,
ECODE(7)TYPENVALUE2191778,
BASIC_SAL(4)TYPEPDECIMALS2VALUE20000,
NOWTYPETVALUE'094500',"givevalueinquotes
HEXA(8)TYPEXVALUE'0123456789ABCDEF',
STRNGTYPESTRINGVALUE'MORGAN''SGATE',"singlequote
"aspartofstring
XSTRNGTYPEXSTRING."XSTRINGdoesnottakeVALUEaddition
***********************************************************************
WRITE:/5'TYPEC:',CNAME,
/5'TYPED:',TODAY,
/5'TYPEF:',FNUM,
/5'TYPEI:',COUNT,
/5'TYPEN:',ECODE,
/5'TYPEP:',BASIC_SAL,
/5'TYPET:',NOW,
/5'TYPEX:',HEXA,
/5'TYPESTRING:',STRNG.
Theoutputwillappearas:
Figure49.OutputofProgram:
YCL_CH04_03_ELEM_DATA_OBJECTS
Intheoutput,typeDisoutputasDDMMYYYY(internalstorageis
YYYYMMDD)withouttheseparatorcharacterbetweendate&monthand
betweenmonth&year.Theseparatorcharacterwasappearingwhenyou
outputthesystemfieldSYDATUMinthepreviousprogram.Thisissue
willbeaddressedinChapter5entitledWRITEStatement(Classical
Reporting).
TypeFisoutputinnormalizedform.TypeFisoutputbytheWRITE
statementin22columnsbydefaultincluding1columnforthesign.TYPE
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
15/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
Fisusedrarelyinbusinessapplications.TypeFwillnotbediscussed
further.
TypeIisoutputwithonlyonethousandseparators,(thousandseparator
comma[,])whenitshouldhavebeenappearingwithtwothousand
separators:oneaftermillionsandoneafterthousandslike987,654,321
insteadof987654,321.ThetypeIbydefaultoutputsthroughaWRITE
statementin11columnswithonecolumnreservedforthesignonthe
right.Sotherewasscopeforonlyonecomma.Thisissuewillbe
addressedinChapter5entitledWRITEStatement(Classical
Reporting).
TypePbydefaultisoutputbytheWRITEstatementincolumnstwicethe
numberofbytesplusonespecifiedinitsdeclaration.(Inyourpresent
context9.)Thesecolumnsincludeonecolumnfordecimal(.)andone
columnforsignontheright.Inyourpresentcasewiththevaluestoredin
thedataobject(20000.00),thereisnoscopeforathousandseparator.
ThisissuewillbeaddressedinChapter5entitledWRITEStatement
(ClassicalReporting).
TypeTisoutputwithouttheseparatorcharacterbetweenhours&minutes
andbetweenminutes&seconds.Theseparatorcharacterwasappearing
whenthesystemfieldSYUZEITinthepreviousprogramwasoutput.
TypeX,XSTRING(hexadecimal)isnotusedinbusinessapplications,
andnomorereferencewillbemadetothesetypes.
ABAPProgram:DeclareInternalDataObjectsConstantsOutput
Ifyouuseaconstantfrequentlyinaprogram,youcandeclareitasa
fixedvaluevariablewiththeCONSTANTSstatement.
TheCONSTANTSStatementsyntax:
CONSTANTS:
<constantname>TYPE<type>[(<length>)][DECIMALS<decimals>]VALUE<value>,
......
TheparametersoftheCONSTANTSstatementsarethesameasforthe
DATAstatement.
Theuseofthe<value>parameterismandatoryfortheCONSTANTS
statementandnotoptionalasintheDATAstatement.Thestartvalue
specifiedwiththe<value>parametercannotbechangedduringthe
executionoftheprogram.
AprogramtodeclareandoutputafewConstants:
Createtheprogram,performthesyntaxcheck,activateandexecute.
REPORTYCL_CH04_04_CONSTANTS.
*********************************************************************
*declareConstantdataobjects,assignvalues(whichismandatory)*
*declarativestatementCONSTANTS.*
*outputconstantdataobjects*
*********************************************************************
***********************************************************************
*keywordCONSTANTSusedtodeclareconstants**
***
*theVALUEclauseistoassignastartingvalue.itismandatory**
***
***********************************************************************
CONSTANTS:INDIAN_REPUBLIC_DAYTYPEDVALUE'19500126',
AMERICAN_INDE_DAYTYPEDVALUE'17760704',
ZEROTYPEIVALUEISINITIAL.
WRITE:/5'INDIAN_REPUBLIC_DAY',INDIAN_REPUBLIC_DAY,
/5'AMERICAN_INDE_DAY',AMERICAN_INDE_DAY.
TheoutputisshowninFigure410.
Figure410.OutputofProgram:YCL_CH04_04_CONSTANTS
Literals
Aliteralisafixedvalue.ABAPdistinguishesbetweentextliteralsand
numberliterals.
Textliterals.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
16/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
Textliteralsaresequencesofalphanumericcharactersenclosedinsingle
quotationmarks.
'SAPAGGermany'
'ABAPWORKBENCH'
Textliteralscanbeupto254characterslong.Ifatextliteralcontainsa
quotationmark,youmustrepeatittoenablethesystemtorecognizethe
contentsasatextliteralandnotastheendoftheliteral.
Toensurethattheprogramsoffermultilingualsupport,donotusetext
literals.Instead,createthemastextsymbolsasyoudidintheHELLO
WORLDprogram.
Numberliterals:
Numberliteralsaresequencesofdigitsthatmaycontainaleadingsign.
Theycancontainupto15digitslike:
123,321,+456
Ifyouneedanonintegervalueoralongernumber,youmustuseatext
literal,whichisconvertedtothecorrecttypeautomatically,suchas:
'12345678901234567890,'+0.58498','8473.67'
ElementaryDataObjectsAssigningValuesorDataMovement
TheMOVEstatementortheassignmentoperator(=)isusedtoassigna
valuetoadataobject.
Syntax
MOVE<f1>TO<f2>.
<f2>=<f1>.
<f4>=<f3>=<f2>=<f1>.
f1canbeavariable,constant,orliteral.
f2,f3,f4havetobetobeavariable.
Thecontentsoff1remainunchanged.
Inthemultipleassignment<f4>=<f3>=etc.,ABAPprocesses
themfromrighttoleft.
ForeachMOVEorassignmentoperator,thesystemchecksthedata
typesofsourceanddestination.Iftypeconversionforthe
combinationisdefined(compatibility),itconvertsthecontentsof
sourcetothedatatypeofdestinationandassignstheconverted
valuetoit.
Therearetwoissueswhendataismovedorassignedfromonedata
objecttoanother:
Compatibility.YoucannotmovetypeDtotypeTandvice
versa.Theyarenotcompatiblewitheachother.Such
assignmentswillresultinsyntaxerror.
Convertibility.SupposeyouhavesourcedataobjectastypeC
anddestinationastypeN.Thisisacceptedbythecompiler.
Aslongasthesourceiscontaining0to9numeralsand
blanks,theassignmentormovementfromsourceto
destinationissuccessful.Ifthesourcecontainscharacters
otherthan0to9orblanks,theassignmentormovement
fails,sourcedataisnotconvertibleandaruntimeerror
occurs.Thisistheissueofconvertibility.
Intherealworld,withsomuchcontrolonthetypeandlengthofdata
objects(domainsetc.),thepossibilityofsuchscenariosisrare.TheSAP
ABAPhelpdocumentationdiscussestheseissueselaborately.
ElementaryDataObjectsAssignmentorMovementwithOffsetsand
Lengths(TypesC,D,NandT)
FortheelementarypredefinedtypesC,D,N,Twhichstoreone
characteroriented,assignmentormovementstatementcanaccess
individualcharacters.
Letthisbedemonstratedwithanexample.WhenyououtputtypeDor
typeT,thedateortimeisoutputbyWRITEstatementwithoutthe
separatorcharacters.DatewasoutputasDDMMYYYY.
LetyourrequirementbethatthedateshouldbeoutputasMMDDYYYY
(USrequirement).Theseparatorcharacterisahyphen().Youwilloutput
thedateinthisformatwiththeMOVEstatementusingoffsetsand
lengths.
InFigure411,whatisavailableinthetypeDasontheleft,needstobe
transformedtotheformasshownontheright.TypeDlengthis8
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
17/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
characters.Thetransformeddateasontherightwillrequire10
characters(2extracharactersforseparators).
Figure411.Source,DestinationforDateTransformation
Theoffsetdatum(firstcharacter)startsas0,not1.
Theoperationsrequiredfortransformationwillbeasfollows:
Moveoffset4,length2fromsource(MM)tooffset0,length2indestination.
Move''tooffset2,length1indestination(Separatorcharacter).
Moveoffset6andlength2fromsource(DD)tooffset3,length2indestination.
Move''tooffset5,length1indestination.(Separatorcharacter).
Moveoffset0andlength4fromsource(YYYY)tooffset6,length4indestination.
ABAPprogram:totransformtypeDfromYYYYMMDDtoMMDDYYYYandoutput:
REPORTYCL_CH04_05_TRANSF_DATE_MOVE.
**************************************************
*DateTransformationwithMOVEOffset&Length**
*convertYYYYMMDDtoMMDDYYYY**
**************************************************
*********************************************
*SourceOffsetsDestinationOffsets*
*012345670123456789*
**
*|Y|Y|Y|Y|M|M|D|D||M|M||D|D||Y|Y|Y|Y|*
**
*********************************************
DATA:SOURCETYPEDVALUE'20130116',
DESTIN(10)TYPEC.
*****************************************
MOVESOURCE+4(2)TODESTIN+0."MOVEMMtoDESTIN
MOVE''TODESTIN+2."MOVE''TODESTIN
MOVESOURCE+6(2)TODESTIN+3."MOVEDDtoDESTIN
MOVE''TODESTIN+5."MOVE''TODESTIN
MOVESOURCE+0(4)TODESTIN+6."MOVEYYYYtoDESTIN
WRITE:/5'SOURCEDEFAULTOUTPUT(DDMMYYYY):',SOURCE,
/5'DESTINTRANSFORMEDOUTUT(MM/DD/YYYY):',DESTIN.
TheexecutionoftheprogramwillgeneratetheoutputshowninFigure4
12.
Figure412.OutputofProgram:
YCL_CH04_05_TRANSF_DATE_MOVE
StructuredDataObjects,OwnDataTypes
Astructureddataobjectisagrouporcollectionofinternalfieldsina
program.Thestructureddataobjectcanbeaccessedasasingleentity
andindividualfieldsinthestructurecanbeaccessedaswell.Youusethe
DATAstatementandmarkthebeginningandtheendofthegroupof
fieldswithBEGINOFandENDOFstatements.Thesyntaxisasfollows:
DATA:BEGINOF<structurename>,
<field1>.....,
..............
ENDOF<structurename>.
Astructureddataobjectcancontainelementarydataobjectsaswellas
complexdataobjects(i.e.,anotherstructureddataobjectorinternal
table).Astructureddataobjectcontainingcomplexdataobjectisnot
discussedinthisbook.
StructuredDataObjectABAPProgram:AccessIndividualFields
REPORTYCL_CH04_06_STRU_DATA_OBJ.
******************************************************
*StructuredDataObjects:AccessIndividualFields**
******************************************************
**************************************************
*declarestructureddataobject.Assign**
*startingvaluestofieldsinthestructured**
*dataobject.outputthesefieldsbyaccessing**
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
18/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
*theindividualfields.**
**************************************************
DATA:BEGINOFCONTACT_MODES,"CONTACT_MODESnameofstrucdataobject
NAME(25)TYPECVALUE'SURAJNAIR',
LAND_LINE(12)TYPENVALUE'009126960021',
CELL_NO(14)TYPENVALUE'00919502102377',
EMAILTYPESTRINGVALUE'snair23@gmail.com',
ENDOFCONTACT_MODES.
WRITE:/5'Name:',CONTACT_MODESNAME,
/5'LandLineNo.:',CONTACT_MODESLAND_LINE,
/5'CellNo.:',CONTACT_MODESCELL_NO,
/5'EmailAddress:',CONTACT_MODESEMAIL.
Inthisprogram,astructureddataobjecthasbeendeclaredusingBEGIN
OF..ENDOF..notationtoindicatethebeginningandendingofthe
structureddataobjectdeclaration.Thefourfieldsinsidethestructure
havebeendeclaredintheusualmanner.Whenyourefertothe
individualfieldsinthestructure,youhavetospecifythestructurename
hyphenfollowedbythefieldname.Thefieldisinsidethestructure.
Thefollowingoutputisgenerateduponthisprogramexecution.
Figure413.OutputofProgram:
YCL_CH04_06_STRU_DATA_OBJ
StructuredDataObject:AccessCompleteStructure
Toaccessacompletestructure,lettherebeacontext.Lettherebetwo
identicalstructures:thatis,havingthesamefieldsinthesameorder,and
eachofthecorrespondingfieldsinthestructuresidenticalintypelength,
etc.Youwillmovedatafromonestructuretoanotherbyreferringtothe
structureandnotindividualfields.
UserDefinedStructureTypes
Youhavetodeclaretwoidenticalstructures.Indeclaringthese
structures,anotherABAPfeatureisintroduced:theuserdefinedtypes.
TheuserdefinedtypescanbedeclaredinanABAPprogramandusedto
refertothesetypestodeclaredataobjectswithinthatprogram.Theuser
definedtypescanalsobedeclaredintheDDICobjectTypeGroup,the
fourthradiobuttonontheSE11openingscreen.Theuserdefinedtypes
declaredintheDDICobjectTypeGroupcanbereferredtoinmultiple
ABAPprogramstodeclaredataobjectsortypes.
WhenyoudeclareuserdefinedtypesinanABAPprogram,theyarejust
definitions.Theyarenotdataobjects,andtheydonotoccupymemory.
Youcannotoperateonthem(i.e.,assignvalues,etc.).Theycanonlybe
referredtodeclaredataobjects.Thedataobjectsdeclaredbyreferringto
themwillhavetheattributes(type,lengthetal.)ofthereferredtypes.
UserdefinedtypesaredeclaredinanABAPprogramwiththekeyword
TYPES.Othernotationsusedindeclaringuserdefinedtypesaresame
aswhendeclaringdatawiththekeywordDATA.
Inyourpresentcontextyouneededtodeclareauserdefinedstructured
type.Youcandeclareanelementaryuserdefinedtype,atableuser
definedtype,andsoon.
StructuredDataObjectinanABAPProgram:UserDefinedTypeinABAP
Program,AccessCompleteStructure
YourABAPprogramwillhaveauserdefinedstructuredtype.Two
identicalstructureddataobjectswillbedeclaredbyreferringtothisuser
definedstructuretype.
REPORTYCL_CH04_07_STRU_DATA_TYP_OBJ1.
************************************************************
*UserDefinedTYPE,ReferencetoStructuredDataObject**
************************************************************
******************************************************
*declareuserdefinedstructuredTYPEwithTYPES**
*statement.declaretwostructureddataobjects**
*(source,destination)byreferringtothisuser**
*definedstructuredTYPE**
*assignvaluestoindividualfieldsofsource**
*useMOVEstatementtotransferentiredataof**
*sourcetodestination.outputfromdestination**
******************************************************
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
19/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
TYPES:BEGINOFCONTACT_MODES_TYPE,"userdefinedstructuredTYPE
NAME(25)TYPEC,
LAND_LINE(12)TYPEN,
CELL_NO(14)TYPEN,
EMAILTYPESTRING,
ENDOFCONTACT_MODES_TYPE.
DATA:CONTACT_MODES_SRCETYPECONTACT_MODES_TYPE,
CONTACT_MODES_DESTTYPECONTACT_MODES_TYPE.
CONTACT_MODES_SRCENAME='ATULVASAN'.
CONTACT_MODES_SRCELAND_LINE='00912696008'.
CONTACT_MODES_SRCECELL_NO='00919502102355'.
CONTACT_MODES_SRCEEMAIL='atulvs@yahoo.co.in'.
MOVECONTACT_MODES_SRCETOCONTACT_MODES_DEST."MOVEstrutostru
WRITE:/5'Name:',CONTACT_MODES_DESTNAME,
/5'LandLineNo.:',CONTACT_MODES_DESTLAND_LINE,
/5'CellNo.:',CONTACT_MODES_DESTCELL_NO,
/5'EmailAddress:',CONTACT_MODES_DESTEMAIL.
Youmightverywellask,whyassignvaluestofieldsof
CONTACT_MODES_SRCE,movethedataofthisstructureto
CONTACT_MODES_DESTandoutput?Whynotdirectlyassignvaluesto
fieldsofCONTACT_MODES_DESTandoutput?Well!Thisisa
demonstrativeprogram.Intherealworld,dataisfetchedintostructured
dataobjectsfromdatabasetables.Dataisrarelyassignedtoliteralsas
hasbeendonehere.
Thiswasademonstration:(a)todeclaredatabyreferringtouserdefined
types,andto(b)MOVEoperationonanaggregateoffieldsorstructure.
TheoutputofthisprogramisshowninFigure414.
Figure414.OutputofProgram:
YCL_CH04_07_STRU_DATA_TYP_OBJ1
UserDefinedTypeinDDIC
Youwillcodethepreviousprogrambyshiftingtheuserdefinedstructured
typefromtheprogramtotheDDICTypeGroup.Youneedtocreatea
TypeGroupandlocateyouruserdefinedstructuredtypeinit.
OntheSE11openingscreen,clicktheTypeGroupradiobutton,and
enteranamefortheTypeGroupasYCLG1(Namespaceonly5
characters).ClickontheCreatebuttonorpressF5.Thefollowingscreen
appearspromptingforShorttext.
Figure415.CreateDDICobjectTypeGroupShorttext
Enterappropriatetext,clickonthe
button,andassign
thepackage($TMP).AnABAPeditorscreenappearswiththestatement
TYPEPOOLYCLG1generatedbythesystem.YCLG1isthenameofyour
TypeGroup.EnteryourstructuredtypelinesunderaTYPESkeyword.
IntheTypeGroupenvironment,eachofthetypesyoudeclaremusthave
theprefixYCLG1_:thatis,thenameoftheTypegroupfollowedbyan
underscore(_).YoucandeclareanynumberoftypesinaTypeGroup.
Theentereddefinitionlinesafterthesyntaxcheck,andactivationwould
appearasshowninFigure416.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
20/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
Figure416.DefineuserdefinedTYPESinTypeGroupYCLG1
StructuredDataObjectinanABAPProgramReferringtoDDICType
Group
TheABAPprogrammustcontainastatementtolisttheTypeGroupsused
intheprogramstartingwiththekeyphraseTYPEPOOLS.Youareusing
onlyoneTypeGroup(i.e.,YCLG1).Thetwostructureddataobjectshave
beendeclared,referringtothestructuredtypeyoudefinedintheType
Group.Therestoftheprogramisthesameasthepreviousone.
REPORTYCL_CH04_08_STRU_DATA_TYP_OBJ2.
*******************************************************************
*UserDefinedTYPEinDDIC,ReferencetoStructuredDataObject**
*******************************************************************
******************************************************
*declaretwostructureddataobjects**
*(source,destination)byreferringtostructured**
*TYPEdefinedinDDICTypeGroup**
*assignvaluestoindividualfieldsofsource**
*useMOVEstatementtotransferentiredataof**
*sourcetodestination.outputfromdestination**
******************************************************
TYPEPOOLSYCLG1."listTypeGroupyouareusinginthisprogram
DATA:CONTACT_MODES_SRCETYPEYCLG1_CONTACT_MODES_TYPE,
CONTACT_MODES_DESTTYPEYCLG1_CONTACT_MODES_TYPE.
CONTACT_MODES_SRCENAME='AGHASHEIK'.
CONTACT_MODES_SRCELAND_LINE='00912696010'.
CONTACT_MODES_SRCECELL_NO='00919502102350'.
CONTACT_MODES_SRCEEMAIL='asheik41@yahoo.co.in'.
MOVECONTACT_MODES_SRCETOCONTACT_MODES_DEST."MOVEstrutostru
WRITE:/5'Name:',CONTACT_MODES_DESTNAME,
/5'LandLineNo.:',CONTACT_MODES_DESTLAND_LINE,
/5'CellNo.:',CONTACT_MODES_DESTCELL_NO,
/5'EmailAddress:',CONTACT_MODES_DESTEMAIL.
Afterthesyntaxcheck,activation,andexecution,theoutputappearsasin
Figure417.
Figure417.OutputofProgram:
YCL_CH04_08_STRU_DATA_TYP_OBJ2
StructuredDataObjects:MOVEStatementSource,DestinationNot
Identical
Intheprecedingprogramsinvolvingdatamovementfromonestructured
dataobjecttoanother,youhadidenticalstructures:thesourceand
destinationcontainedthesamenumberoffields,theorderofthefields
wassame,andeachofthefieldsinthesourcewasidenticaltothe
correspondingfieldinthedestinationasfarasTYPE,length,etc.The
MOVEstatement,whenoperatedonstructuredtypes,treatsanentire
aggregateoffieldsinthestructureasonefieldofTYPECthebytesinthe
sourcearetransferredtothecorrespondingbytenos.inthedestination.
Thisidenticalnessofsourceanddestinationstructureddataobjectsmight
notalwaysbeso.Insuchacase,youshouldnotoperatetheMOVE
commandatthestructurelevel.PerhapsyoucouldissueaMOVE
statementforindividualfields.Ifthereare10fieldstobetransferred
fromonestructuretoanother,issue10MOVEorassignmentstatements.
ThereisavariationofaMOVEstatementthatletsyoucopythefieldsofa
sourcestructuretothefieldsofadestinationstructure.Thetransferof
dataisbasedonthenamesofthefieldsofsourceanddestinationbeing
identical.Thecontentsoffieldsindestinationwhosenamesdonotmatch
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
21/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
withnamesinthesourcehavetheircontentsundisturbed.Thedata
movementisfieldwise.
Syntax
MOVECORRESPONDING<structure1>TO<structure2>.
Figure418representsthisgraphically.Therewillbenodatatransferfor
LAND_LINEsincethereisnofieldwiththisnameinthedestination.
Also,thefieldCELL_NOlengthis14bytesinsourceand12bytesin
destination.ThedatamovementforTYPENisrighttolefttheleading
firsttwodigits00willgettruncatedinthedestination.
Figure418.OperationofMOVECORRESPONDINGinStructured
DataObjects
TheABAPprogramforthisscenariois
REPORTYCL_CH04_09_STRU_MOVE_CORR.
*************************************************
*StructuredDataObjectsMOVECORRESPONDING**
*************************************************
*******************************************************
*declaretwostructureddataobjectswithonefield**
*namedifferinginsource&destination**
***
*assignvaluestoindividualfieldsofsourceand**
*destination**
***
*useMOVECORRESPONDINGstatementtotransferfrom**
*sourcetodestination.outputfromdestination**
*******************************************************
DATA:BEGINOFCONTACT_MODES_SRCE,
NAME(25)TYPECVALUE'GURUDAS',
LAND_LINE(12)TYPENVALUE'00912696113',
CELL_NO(14)TYPENVALUE'00919592302444',
EMAILTYPESTRINGVALUE'gu_das@gmail.com',
ENDOFCONTACT_MODES_SRCE,
BEGINOFCONTACT_MODES_DEST,
NAME(25)TYPECVALUE'ZZZZZZZZ',
LAND_LINE_NO(12)TYPENVALUE'999999999999',
CELL_NO(12)TYPENVALUE'999999999999',"lengthdiffersfromsource
EMAILTYPESTRINGVALUE'ZZZZZZZZZZZZZZZZ',
ENDOFCONTACT_MODES_DEST.
MOVECORRESPONDINGCONTACT_MODES_SRCETOCONTACT_MODES_DEST.
WRITE:/5'Name:',CONTACT_MODES_DESTNAME,
/5'LandLineNo.:',CONTACT_MODES_DESTLAND_LINE_NO,
/5'CellNo.:',CONTACT_MODES_DESTCELL_NO,
/5'EmailAddress:',CONTACT_MODES_DESTEMAIL.
TheoutputisshowninFigure419.
Figure419.OutputofProgram:
YCL_CH04_09_STRU_MOVE_CORR
Date,TimeArithmetic
YoucanperformsomebasicarithmeticoperationsontypesDandT.You
adddaystoadatetoderiveafuturedate,subtractdaysfromadateto
deriveapastdate,andderivethedifferenceindaysbetweentwodates.
Similarly,youcanaddsecondstoatimetoderiveadvancedtime,
subtractsecondsfromatimetoderiveatimeinthepastandthe
differenceinsecondsbetweentwotimes.
DateArithmeticABAPProgram
AnABAPprogramdemonstratingdatearithmeticiscoded.
REPORTYCL_CH04_10_DATE_ARITHM.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
22/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
********************
*DateArithmetic**
********************
*****************************************************
*inputoftwodatesDATE1DATE2through**
*PARAMETERSstatement(specialdataobject)**
*theDEFAULTclausewithPARAMETERSassigns**
*startingvaluetothepromptvariablesjustlike**
*VALUEfordataobjectsinDATAstatement**
***
*inputofDAYS(TYPEI)**
***
*calculate&outputdifferencebetweenDATE1,DATE2**
*calculate&outputdatebyaddingDAYStoDATE2**
*calculate&outputthelastdayofmonthofDATE1**
***
*bitofjugglarycodetocalculatelastdayof**
*month.youarefirstderivingthedateasof**
*firstdayofnextmonth,nextsubtracting1from**
*thatdate.(therewouldbebetterways)**
***
*theIFstatementhasnotbeenintroduced,but**
*shouldnotbeaproblem**
***
*VARisTYPEI,outputsin11columnsbydefault.**
*(5)sigifiestheoutputmustappearin5columns**
***
*whenyououtputTYPEDdataobjects,youare**
*specifyingtheclauseDD/MM/YYYYforseparator.**
*youarenotabletooutputseparatorofyour**
*choice.theperiod(.)asseparatrisappearing**
*fromglobalsetting/masterrecord**
*****************************************************
*****************************************************
*whenyoupressF8systemwillpromptforinput**
*DATE1,DATE2,DAYS.whenyoufinishedwithinput**
*pressF8againtoobtainoutput.**
*pressF3toreturnfromoutputtoinputscreen**
*pressF3toreturnfrominputscreentoprogram**
*****************************************************
DATA:VARTYPEI,
DATETYPED,
YEAR(4)TYPEN,
MONTH(2)TYPEN,
DAY(2)TYPEN.
PARAMETERS:DATE1TYPEDDEFAULT'20131025',
DATE2TYPEDDEFAULT'20121125',
DAYSTYPEIDEFAULT100.
*************************************************
VAR=DATE1DATE2."differencebetweenDATE1,DATE2
WRITE:/5'Diff.betweenDates:',DATE1DD/MM/YYYY,
DATE2DD/MM/YYYY,'=',(5)VAR.
DATE=DATE2+DAYS."thedateahead/behindofDATE2byDAYS
WRITE:/5DATE2DD/MM/YYYY,'+',(5)DAYS,'=',DATEDD/MM/YYYY.
YEAR=DATE1+0(4)."offset&lengthused
MONTH=DATE1+4(2).
IFMONTH<12.
MONTH=MONTH+1.
ELSE.
MONTH=1.
YEAR=YEAR+1.
ENDIF.
DATE+0(4)=YEAR."gettofirstdayofnextmonth
DATE+4(2)=MONTH.
DATE+6(2)='01'.
DATE=DATE1."subtract1fromfirstdayofnextmonth
"forlastdayofmonth
DAY=DATE+6(2).
WRITE:/5'Lastdayofmonthdate',DATE1DD/MM/YYYY,'=',DAY.
Whenyouexecutetheprogramwiththedefaultvalues,theoutputin
Figure420isgenerated.
Figure420.OutputofProgram:
YCL_CH04_10_DATE_ARITHM
YoucanattemptanexercisewithTYPETonaparallelbasis.
ArithmeticNumericalOperations
BasicArithmeticOperations/Operators
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
23/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
Thearithmeticassignmentstatementhasthesyntax
[COMPUTE]<n>=<expression>.
ThewordCOMPUTEisoptional.
Thefield<n>isassignedtotheresultofthearithmeticexpression.
Thenumericalprecisionisdefinedbytheoperandofthenumerical
operationthathasthehighesthierarchylevel.Thesystemtreatsthe
targetfield<n>andthefloatingpointfunctionsasoperands.The
orderofthehierarchylevelsisI,P,andF.ABAPconvertsall
numbersofanumericaloperationintoitshierarchicallyhighest
datatypethatoccursintheoperation.Thenthesystemexecutesthe
operationwiththeconvertednumbers.
Theorderorprecedenceofoperationsorevaluationisasfollows:
Expressionsinparentheses
Functions
**
Exponentiation
*/MOD/DIV(Multiplication,division,&MOD)
+(additions&subtractions)
Whenwritingarithmeticexpressionsandstatements,youmustleavea
blankbeforean=signandafteranequalsign.Youmustalsoleavea
blankbetweenanoperatorandoperandlike:
TAX=(TAX_RATE/100)*TAX_AMOUNT.
Inadditiontothemathematicaloperators,youcanusetheADD,
SUBTRACT,MULTIPLY,DIVIDE...statements.Theusageoftheseis
rare.Mostpeoplesticktomathematicaloperators.
FunctionsCommontoAllNumericDataTypes
Table44.NumericFunctions
Function
Description
ABS(X)
Absolutevalueoftheargument
SIGN(X)
=1ifX>0=0ifX=0=1IfX<0
CEIL(X)
Smallestintegervaluenotsmallerthanthe
argument
FLOOR(X)
Largestintegervaluenotlargerthanthe
argument
TRUNC(X)
Integerpartofargument
FRAC(X)
Fractionpartofargument
FloatingPointFunctions
Therearefloatingpointfunctions.YoucanrefertothePDFdocument
ABAPProgramming(BCABA)underBasicStatements
NumericalOperations
MathematicalFunctions.However,theseare
notofmuchsignificanceinbusinessapplications.
ArithmeticOperationsonStructures
SimilartoaMOVECORRESPONDINGstatementinvolvingidentical
fieldnamesinStructures,youcanperformarithmeticoperationson
fieldsoftwostructureshavingidenticalfieldnamesandtypenumerical:
ADDCORRESPONDING
SUBTRACTCORRESPONDING
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
24/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
MULTIPLYCORRESPONDING
DIVIDECORRESPONDING
Youwillnothaveanyexclusivehandsonprogramsforarithmetic
operations.Mostofyouwillhavealreadybeexposedtotheseconcepts.
ThearithmeticoperationsinABAPareverysimilartothatinother
computerlanguages.Youwillbeperformingarithmeticoperationsinthe
subsequentchapters,whenandasascenariodemandsit.
StringOperations
Youarecreatingandexecutingahalfdozenhandsonprogramstocover
themajorfeaturesofstringoperationsorstatements.
AnABAPProgramDemonstratingTRANSLATE.UPPERCASE/LOWER
CASEisCoded
REPORTYCL_CH04_11_TRANSLATE.
***************************************
*TRANSALATE:UPPERCASE,LOWERCASE**
***************************************
************************************************
*takeastringinputthroughPARAMETERS**
*variableISTRING**
***
*inthePARAMETERSstatementthephrase**
*LOWERCASEenablesinputinLOWERaswell**
*asUPPERcase.(casesensitivity)bydefault**
*thePARAMETERSstatementacceptsonlyUPPER**
*casei.e.evenifyouenterlowercaseit**
*isconvertedtoUPPERcase.**
***
*theISTRINGisassignedtoOSTRING.the**
*TRANSALATE..TOUPPERCASEisperformedon**
*OSTRING.OSTRINGisoutput**
***
*theISTRINGisassignedtoOSTRING.the**
*TRANSALATE..TOLOWERCASEisperformedon**
*OSTRING.OSTRINGisoutput**
************************************************
DATA:OSTRING(50)TYPEC.
PARAMETERS:ISTRING(50)TYPECLOWERCASEDEFAULT
'MpHasISAnH.p.CoMPanY'.
OSTRING=ISTRING.
TRANSLATEOSTRINGTOUPPERCASE.
WRITE:/5'OriginalString:',ISTRING,
/5'UPPERCASESTRING:',OSTRING.
OSTRING=ISTRING.
TRANSLATEOSTRINGTOLOWERCASE.
WRITE:/5'lowercasestring:',OSTRING.
TheprogramwiththeDEFAULTvalueofISTRINGwillgeneratethe
outputinFigure421.
Figure421.OutputofProgram:YCL_CH04_11_TRANSLATE
IntheABAPeditor,whenyoupositionthecursoronakeywordandpress
F1,thesystemopensanewwindow.ThenewwindowdisplaystheABAP
KeywordDocumentationforthekeywordonwhichF1waspressed.Ifyou
pressedF1onthekeywordTRANSLATEintheABAPprogram,thenthe
screenshowninFigure422isdisplayed.
Figure422.ABAPKeywordDocumentation
KeepvisitingtheABAPKeywordDocumentationasoftenasyoucan.
AnABAPProgramDemonstratingCONCATENATEisCoded
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
25/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
TheCONCATENATEstatementhasbeenusedtotransformthedatefrom
YYYYMMDDtoMM/DD/YYYYformatandoutput.Earlieryouhadused
theMOVEstatementtoimplementthis.Asyouwillobserve,thisisa
betteroption.TheCONCATENATEstatementjoinsmultiplesource
stringsintoonedestinationstringwithanoptionalseparatorcharacter
string.
Ifthedestinationstringisinsufficientforaccommodatingtheresult,
truncationwilloccurontherightsideandnoruntimeerroroccurs.
REPORTYCL_CH04_12_CONCATENATE.
*******************************************************
*CONCATENATEJoinMultipleStringsIntoOneString*
*******************************************************
********************************************
*inputadateIDATEthroughPARAMETERS**
*useCONCATENATEstatementtojoinMM**
*[IDATE+4(2)]'/'DD[IDATE+6(2)]'/'**
*YYYY[IDATE+0(4)]inCDATE.CDATEwill**
*willcontainMM/DD/YYYY.**
*OutputIDATEandCDATE**
***
*repeattheCONCATENATEstatementby**
*specifyingseparatorstring/character**
*OutputIDATEandCDATE**
********************************************
DATA:CDATE(10)TYPEC.
PARAMETERSIDATETYPEDDEFAULT'20130116'.
CONCATENATEIDATE+4(2)'/'IDATE+6(2)'/'IDATE+0(4)INTOCDATE.
WRITE:/5IDATE,CDATE.
CONCATENATEIDATE+4(2)IDATE+6(2)IDATE+0(4)INTOCDATE
SEPARATEDBY'/'."useofseparatorcharacter
WRITE:/5IDATE,CDATE.
TheprogramwiththeDEFAULTvalueofIDATEwillgeneratethe
followingoutput:
Figure423.OutputofProgram:
YCL_CH04_12_CONCATENATE
AnABAPProgramDemonstratingSPLIT,theReverseof
CONCATENATEisCoded
TheSPLITstatementbreaksonesourcestringintomultipledestination
strings.Youhavetospecifyaseparatorstring/characterthatdetermines
thesplitting.IfisblankorSPACEisspecified,thiswillsplitasentence
intoitsconstituentwords.
Iftherearenotenoughdestinationstrings,theresidualstringafterthe
lastsplitwillgointothedestinationstringvariableappearinglastinthe
statement.Ifthelastvariableinthestatementisinsufficientfor
accommodatingtheresidualstring,truncationwilloccurontherightside
andnoruntimeerroroccurs.
REPORTYCL_CH04_13_SPLIT.
*********************************************************
*SPLITBreakOneSourceStringIntoMultipleStrings*
*(BreakIntoWords)*
*********************************************************
*****************************************************
*takeinputstringasISTRINGthroughPARAMETERS**
*5destinationvariablesprovided**
*operatetheSPLITstatementonISTRINGATSPACE**
*outputdestinationvariables**
*****************************************************
DATA:STR1(10)TYPEC,
STR2(10)TYPEC,
STR3(10)TYPEC,
STR4(10)TYPEC,
STR5(10)TYPEC.
*************************************************
PARAMETERS:ISTRING(50)TYPECDEFAULT'NIGHTATTHEMUSEUM'.
SPLITISTRINGATSPACEINTOSTR1STR2STR3STR4."SPACEisaSystemData
"Objectblank/s
WRITE/5:STR1,
STR2,
STR3,
STR4.
TheprogramwiththeDEFAULTvalueofISTRINGwillgeneratethe
followingoutput:
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
26/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
Figure424.OutputofProgram:YCL_CH04_13_SPLIT
Avariationofthisstatementthatreturnsthedestinationstringsinan
arrayismostlyused.ThisvariationwillbecoveredinChapter6entitled
InternalTables.
AnABAPProgramDemonstratingtheFunctionSTRLEN()isCoded
TheSTRLEN()functionreturnsthelengthofastringvariable.The
leadingblanksarecountedandthetrailingblanksarenotcountedinthe
length.
REPORTYCL_CH04_14_STRLEN.
*********************************************************
*STRLEN()returnsthelengthofastringvariable*
*********************************************************
DATA:LEN(2)TYPEPDECIMALS0.
PARAMETERS:ISTRING(50)TYPECDEFAULT'ABAPWORKBENCH'.
LEN=STRLEN(ISTRING).
WRITEAT:/5'StringLengthof:',(LEN)ISTRING,(2)LEN.
TheprogramwiththeDEFAULTvalueofISTRINGwillgeneratethe
outputasinFigure425.
Figure425.OutputofProgram:YCL_CH04_14_STRLEN
AnABAPProgramDemonstratingtheStatementCONDENSEisCoded
TheCONDENSEstatementremovestheleading/leftsideblanksand
reducestheembeddedblankstooneorzero.
REPORTYCL_CH04_15_CONDENSE.
***********************
*CONDENSEStatement**
***********************
****************************************************************
*takeinputstringasISTRINGthroughPARAMETERS**
***
*assignISTRINGtoOSTRING.operateCONDENSEonOSTRING.**
*outputOSTRING**
***
*assignISTRINGtoOSTRING.operateCONDENSEonOSTRINGwith**
*NOGAPS.outputOSTRING**
***
*CONDENSEstatementoperation:**
*(a)removesallleading/leftsideblanks.(b)itreduces**
*embeddedblankstooneblank.(c)iftheadditionNOGAPS**
*isspecified,itreducesembeddedblankstozeroi.e.**
*embeddedblankswillberemovedtotally**
****************************************************************
DATAOSTRING(50)TYPEC.
PARAMETERS:ISTRING(50)TYPECDEFAULT
'ABAPLANGUAGEBASICS'.
MOVEISTRINGTOOSTRING.
CONDENSEOSTRING.
WRITE:/5'OriginalString:',ISTRING,
/5'CondenseString:',OSTRING.
MOVEISTRINGTOOSTRING.
CONDENSEOSTRINGNOGAPS.
WRITE:/5'CondenseString(NOGAPS):',OSTRING.
TheprogramwiththeDEFAULTvalueofISTRINGwillproducean
outputasinFigure426.
Figure426.OutputofProgram:YCL_CH04_15_CONDENSE
Notallstringoperatorsarecoveredhere.Anystringoperatoryoumight
needinascenariowouldbeintroducedinthescenariocontext.
ProgramInternalFlowControl
Likeinanyotherprogramminglanguage,ABAPalsoexecutes
statementssequentiallyoneafteranother.Thissequentialexecutionis
brokenbythesocalledflowcontrolstatements.ABAP,likeanyother
fourthgenerationlanguageiseventdriven.InABAPtherearetwotypes
offlowcontrolstatements:(i)InternalControland(ii)ExternalControl.
Theinternalflowcontrolconsistsofthefollowingcategoriesof
statements:
Table45.InternalFlowControlStatementCategories
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
27/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
ConditionTesting
IF,ELSE,ELSEIF,
ENDIF
Singlevariableequalitytesting
CASE,WHEN,
ENDCASE
Unconditionalloopingorrepetitive
DO,ENDDO
procedures
Conditionalloopingorrepetitive
WHILE,
procedures
ENDWHILE
Modularization,callingexternal
PERFORM,CALL
procedures
Theexternalflowcontrolconsistsofevents.Eventswillbeintroducedin
Chapter5entitledWRITEStatement(ClassicalReporting).
Conditions,ConditionalOperators
Theinternalflowofprogramsiscontrolledwithconditions.Toconstruct
acondition,logicalexpressionsareusedthatcomparedatafieldsas
follows:
...<f1><conditionaloperator><f2>...
Theexpressioncomparestwofields(operands)<f1>,<f2>.Thesefields
canbedatabasefields,programdataobjects,literals,orconstants.
Structureddatatypescanalsobeusedasoperands.Structuresare
comparedcomponentbycomponent,andnestedstructuresarebroken
downintoelementaryfields.TheABAPsupportsthefollowing
conditionaloperators.
ConditionalOperators
Operator
Meaning
EQ=
EQUALTO
NE<>><
NOTEQUALTO
LT<
LESSTHAN
LE<=
LESSTHANOREQUALTO
GT>
GREATERTHAN
GE>=
GREATERTHANOREQUALTO
BETWEEN
BETWEEN
ISINITIAL
ISINITIAL
Iffieldsofdifferentdatatypesarecompared,theymustbeconvertible.
Beforeperformingthecomparison,thesystemexecutesanautomatic
conversion.Theconversionisaccordingtothefollowinghierarchical
rules:
Ifoneoftheoperandsisafloatingpointnumber(typeF),the
systemconvertstheotheroperandsalsototypeF.
Ifoneoftheoperandisapackeddecimalnumber(typeP,)the
systemconvertstheotheroperandalsototypeP.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
28/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
Ifoneoftheoperandsisadatefieldtype(typeD)oratimefield
(typeT),thesystemconvertstheotheroperandstotypeDorT.
Comparisonbetweendateandtimefieldsarenotallowed.
Ifoneoftheoperandsisacharacterfield(typeC)andtheotherisa
hexadecimalfield(typeX),thesystemconvertstypeXtotypeC.
Ifoneoftheoperandsisacharacterfield(typeC)andtheotherisa
numericstring(typeN),thesystemconvertsboththeoperandsto
typeP.
ABAPalsosupportsspecialcomparisonpatternoperatorsforTYPESC,D,
N,andT.LookinthePDFdocumentABAPProgramming(BCABA)
underBasicStatements
LogicalExpressions
ComparingStrings.
LogicalOperators
AND
OR
NOT
TheIFConditionStatement
Syntax&somevariations
ABAPallowsunlimitednestingofIFENDIFstatementblocks,butthey
mustterminatewithinthesameprocessingblock.SoanIFENDIFblock
cannotcontainaneventkeyword.
ConditionalBranchingwithCASE
Syntax&somevariations
Toexecutedifferentmutuallyexclusivestatementblocksdependingon
thecontentsofaparticulardataobject,youcanusetheCASEstatement
asfollows:
CASE<f>.
WHEN<f1>.
<statementblock>
WHEN<f2>.
<statementblock>
WHEN...
......
WHENOTHERS.
<statementblock>
ENDCASE.
ThesystemexecutesthestatementblockaftertheWHENstatementifthe
contentsof<f>equalsthecontentsof<fi>,itandcontinuesprocessing
aftertheENDCASEstatement.Thestatementblockaftertheoptional
WHENOTHERSstatementisexecutedifthecontentsof<f>arenot
equalanyofthe<fi>contents.Thelaststatementblockmustbe
concludedwithENDCASE.
TheUnconditionalLoops:DOENDDO
Repetitiveexecutionofastatementblockisachievedbythe
unconditionalloopstatementDO.
Syntax
DO[<n>TIMES][VARYING<f>FROM<f1>NEXT<f2>].
<statementblock>
ENDDO.
ThesystemprocessesthestatementblockbetweenDO&ENDDO
repeatedlyuntilitfindsanEXIT,STOPstatement.
Thenumberoftimestheloopshouldperformrepeatedlycanbe
optionallyspecifiedbytheTIMESoption.Theparameter<n>can
bealiteralorvariable.If<n>iszeroorlessthanzero,thesystem
doesnotprocesstheloop.
Eachtimetheexecutionproceedsfromthestarttotheendofthe
loop,itiscalledalooppass.ThesystemfieldSYINDEXcontains
thevalueofthelooppassofthecurrentloopbeingexecuted.
Itshouldbeensuredthattheloopisexecutedendlesslyorinfinite
times.
Loopscanbenestedoneinsideanotheranynumberoftimes.The
unconditionalloopDOcanbecombinedinthenestingwiththe
othertypeofloop,theconditionalloopstatement:WHILE
ENDWHILE.
TheVARYINGoptionisusedinfrequently,butitsoperationcanbe
referencedinthemanualABAPProgramming(BCABA)under
BasicStatements
Loops.
Threestatements:EXIT,CONTINUE,andCHECKoperateinsidethe
loopasfollows:
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
29/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
EXIT(TerminateLoop)isforexitingandcomingoutofthecurrent
loopaltogether.
CONTINUE(TerminateLoopPassUnconditionally)isfor
bypassingthecurrentpassoftheloopandstartingtheexecutionof
thenextpass,ifany.
TheCHECK(TerminateaLoopConditionally)statementiftrue
allowsthestatementblockfollowingittobeexecuted.Ifthecheck
statementevaluatestobefalse,thestatementblockfollowingitis
notexecuted,anditisequivalenttotherestofloopstatements
beingbypassedforthatpassoftheloop.
TheConditionalLoops:WHILEENDWHILE
Conditionalrepetitiveexecutionofastatementblockisachievedbythe
conditionalloopstatementWHILE.
Syntax
WHILE<condition>[VARYING<f>FROM<f1>NEXT<f2>].
<statementblock>
ENDWHILE.
The<condition>canbeasimpleconditionoracompound
conditionlikeinIFstatements.
ThesystemprocessesthestatementblockbetweenWHILE&
ENDWHILErepeatedlyuntilitfindsanEXITorSTOPstatement
orthe<condition>evaluatesasfalse.
TheVARYINGoptionworksthesamewayasforunconditional
loopDOENDDO.
AlsotheCONTINUEandCHECKstatementsworkthesamewayas
fortheunconditionalloops.
TheinternalflowcontrolstatementsinABAPissimple,andyouarenot
performinganyspecifichandsonprogramsonthese.Intheforthcoming
chapters,youwillhavetheoccasiontousethese.
Youwillthoughhaveonehandsonprogramdemonstratingthebehavior
ofthesystemfieldSYINDEXassociatedwithloopingconstructs.This
systemfieldassumesthevalueofthepassnumberofthecurrentloop.
AnABAPprogramcodedfordemonstratingthebehaviorofsystemfield
SYINDEXinatwolevelloopnesting.
REPORTYCL_CH04_16_SY_INDEX.
******************************************************
*DemonstratetheBehaviorofSystemFieldSYINDEX**
******************************************************
***************************************************************
*SYINDEXcontainsthepassnoofcurrentloop**
***
*ifyouareintheouterloop,itwillcontainpassnoof**
*outerloop.ifyouareintheinnerloop,itwill**
*containpassnoofinnerloop**
***
*theinnerloopwillperformtwice(IFSYINDEX>2.EXIT.)**
*foreverypassofouterloop.theouterloopwill**
*performthrice(IFSYINDEX>3.EXIT.)**
***
*theWRITEstatementinouterloopoutputsstartingfrom**
*column5.SYINDEXisTYPEI.TYPEIoutputsbydefaultin**
*11columns.SYindexisbeingoutputintwocolumns**
*(itsvalueneverexcedding3inthisprogram)**
***
*theWRITEstatementininnerloopoutputsstartingfrom**
*column10.**
***************************************************************
DO.
IFSYINDEX>3.
EXIT.
ENDIF.
WRITE:/5'OuterLoop:',(2)SYINDEX.
DO.
IFSYINDEX>2.
EXIT.
ENDIF.
WRITE:/10'InnerLoop:',(2)SYINDEX.
ENDDO.
ENDDO.
TheprogramwillproduceanoutputasinFigure427.
Figure427.OutputofProgram:YCL_CH04_16_SY_INDEX
DetermineAttributesofDataObjects
Sometimes,youneedtodetermineinaprogram,theattributesofadata
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
30/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
objectdeclaredbyreferencetoaDDICobject.Theattributesthatcanbe
determinedaretype(elementarytypes:C,D,F,I,N,P,T,X,STRING,
XSTRINGReferencetypesComplextypes:StructureorTable),length,
decimals,outputlength,etc.
TheDESCRIBEFIELDstatementisavailabletoascertaintheattributes
ofadataobject.ThesyntaxoftheDESCRIBEFIELDstatement:
DESCRIBEFIELD<fieldname>[TYPE<type>][LENGTH<length>IN{BYTE|CHARACTER}MODE]
[DECIMALS<decimals>][COMPONENTS<components>]
[OUTPUTLENGTH<outputlength>][EDITMASK<editmask>][HELPID<helpid>].
DESCRIBE
Keyphrase
FIELD
<fieldname>
Nameofdataobjectwhoseattributesareto
bedetermined
TYPE
Keyword
<type>
Variableinwhichthetypewillbereturned.
<type>shouldbetypeCandthe
appropriatelength(seeTable46forthe
differenttypesreturned)
LENGTH
Keyword
<length>
Variableinwhichthelengthisreturnedas
numberofcharacters/bytes<length>
desirablybetypeI
IN
KeyPhrase.Lengthisreturnedin
CHARACTER
CharacterCount.Thisshouldbegivenfor
MODE
TYPESC,D,N,andTOnly
INBYTE
KeyPhrase.LengthisreturnedinByte
MODE
Count.Thiscanbegivenforelementary
andstructureTYPES
DECIMALS
Keyword(relevantonlyforTYPESFandP)
<decimals>
Variableinwhichthenumberofdecimalsis
returned.<decimals>woulddesirablybeof
typeI(relevantonlyforTYPESFandP)
COMPONENTS
KeyPhrase
<components>
Returnsnumberoffieldsinastructure.
Relevantforstructuretype
OUTPUT
KeyPhrase
LENGTH
<output
Variableinwhichtheoutputlengthis
length>
returned.Ifthisfieldisassociatedwitha
domain,theoutputlengthispickedupfrom
here.Else,theoutputlengthisasperthe
defaultoutputlengthintheWRITE
statement
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
31/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
EDITMASK
KeyPhrase
<editmask>
FieldinwhichEDITMASKisreturned.
EDITMASKiscoveredinChapter5
entitledWRITEStatement(Classical
Reporting).
HELPID
KeyPhrase
<helpid>
FieldinwhichHELPIDisreturnedHELP
IDiscoveredinChapter9entitled
SELECTIONSCREEN
ThedifferenttypesreturnedbytheDESCRIBEFIELDstatement(other
thantheelementarytypesthatarereturnedasC,D,F,I,N,P,T,
X,STRING,andXSTRING)arelistedinTable46.
Table46.DESCRIBEFIELD:TYPEReturnValues
Description
ReturnType
Value
ElementaryABAPTYPESTRING
ElementaryABAPTYPEXSTRING
ObjectReference
DataReference
DDICINT1
DDICINT2
Flatstructure(structurewithnoembedded
structureortable)
DeepStructure(structurewithembedded
structureortable)
InternalTable
AnABAPprogramcodedfordemonstratingtheDESCRIBEFIELD
statement:
REPORTYCL_CH04_17_DESCRIBE_FIELD.
********************************************************
*DESCRIBEFIELD:DetermineAttributesofDataobjects*
********************************************************
***********************************************************************
*declareelementarydataobjectsreferringtoDDICtablefields**
*declareelementarydataobjectreferringtoDDICdataelement**
*declarestructuredataobjectreferringtoDDICtabledefinition**
*declareelementaryTYPESTRING**
***
*useDESCRIBEFIELDstatementtodetermineattributes**
*outputattributes**
***
***********************************************************************
DATA:NAME1TYPEKNA1NAME1,"DDICtablefield
FKDATTYPEVBRKFKDAT,"DDICtablefield
NETWRTYPEVBRKNETWR,"DDICtablefield
TEXT1TYPETBOOKSHOPTEXT1,"DDICtablefield
LENGTHTYPETBOOKSHOPLENGTH,"DDICtablefield
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
32/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
WAERSTYPEWAERS,"referencetodataelement
INT1TYPEMCSAPINT1,"referencetodataelement
VBRKTYPEVBRK,"referencetotablestructure
STRNGTYPESTRING,
TYP(1)TYPEC,
LENTYPEI,
OLENTYPEI,
DECITYPEI,
COMPOTYPEI.
**************************************************************************
DESCRIBEFIELDNAME1TYPETYP.
IFTYP='C'ORTYP='D'ORTYP='N'ORTYP='T'.
DESCRIBEFIELDNAME1LENGTHLENINCHARACTERMODE.
ELSE.
DESCRIBEFIELDNAME1LENGTHLENINBYTEMODE.
ENDIF.
WRITE:/5'KNA1NAME1TYPE&LENGTH:',TYP,
(3)LEN.
*********************************************************************
DESCRIBEFIELDFKDATTYPETYP.
IFTYP='C'ORTYP='D'ORTYP='N'ORTYP='T'.
DESCRIBEFIELDFKDATLENGTHLENINCHARACTERMODE.
ELSE.
DESCRIBEFIELDFKDATLENGTHLENINBYTEMODE.
ENDIF.
WRITE:/5'VBRKFKDATTYPE&LENGTH:',TYP,
(3)LEN.
**********************************************************************
DESCRIBEFIELDNETWRTYPETYP.
IFTYP='C'ORTYP='D'ORTYP='N'ORTYP='T'.
*DESCRIBEFIELDNETWRLENGTHLENINCHARACTERMODE.
ELSE.
DESCRIBEFIELDNETWRLENGTHLENINBYTEMODE.
ENDIF.
IFTYP='F'ORTYP='P'.
DESCRIBEFIELDNETWRDECIMALSDECI.
ENDIF.
DESCRIBEFIELDNETWROUTPUTLENGTHOLEN.
WRITE:/5'VBRKNETWRTYPE,LENGTHOUTPUTLENGTH&DECIMALS:',TYP,
(3)LEN,(2)OLEN,(2)DECI.
***********************************************************************
DESCRIBEFIELDTEXT1TYPETYP.
IFTYP='C'ORTYP='D'ORTYP='N'ORTYP='T'.
DESCRIBEFIELDTEXT1LENGTHLENINCHARACTERMODE.
ELSE.
DESCRIBEFIELDTEXT1LENGTHLENINBYTEMODE.
ENDIF.
WRITE:/5'TBOOKSHOPTEXT1TYPE&LENGTH:',TYP,
(4)LEN.
*********************************************************************
DESCRIBEFIELDLENGTHTYPETYP.
IFTYP='C'ORTYP='D'ORTYP='N'ORTYP='T'.
*DESCRIBEFIELDLENGTHLENGTHLENINCHARACTERMODE.
ELSE.
DESCRIBEFIELDLENGTHLENGTHLENINBYTEMODE.
ENDIF.
WRITE:/5'TBOOKSHOPLENGTHTYPE&LENGTH(DDICTYPEINT2):',TYP,
(3)LEN.
*******************************************************************
DESCRIBEFIELDWAERSTYPETYP.
IFTYP='C'ORTYP='D'ORTYP='N'ORTYP='T'.
DESCRIBEFIELDWAERSLENGTHLENINCHARACTERMODE.
ELSE.
DESCRIBEFIELDWAERSLENGTHLENINBYTEMODE.
ENDIF.
WRITE:/5'CURRENCYCODEWAERSTYPE&LENGTH:',TYP,
(3)LEN.
********************************************************************
DESCRIBEFIELDINT1TYPETYP.
IFTYP='C'ORTYP='D'ORTYP='N'ORTYP='T'.
*DESCRIBEFIELDINT1LENGTHLENINCHARACTERMODE.
ELSE.
DESCRIBEFIELDINT1LENGTHLENINBYTEMODE.
ENDIF.
WRITE:/5'DDICTYPEINT1&LENGTH(REF.TODATAELEMENT):',TYP,
(3)LEN.
************************************************************************
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
33/34
1/5/2016
Chapter4:ABAPLanguageBasicsSAPABAP:HandsOnTestProjectswithBusinessScenarios
DESCRIBEFIELDVBRKTYPETYPCOMPONENTSCOMPOLENGTHLENINBYTEMODE.
WRITE:/5'VBRKTYPE,LENGTH&CMPONENTS:',TYP,(4)
LEN,(3)COMPO.
************************************************************************
DESCRIBEFIELDSTRNGTYPETYP.
IFTYP='C'ORTYP='D'ORTYP='N'ORTYP='T'.
*DESCRIBEFIELDSTRNGLENGTHLENINCHARACTERMODE.
ELSE.
DESCRIBEFIELDSTRNGLENGTHLENINBYTEMODE.
ENDIF.
WRITE:/5'LOCALLYDEFINEDTYPE''STRING''TYPE&LENGTH:',
TYP,(3)LEN.
Theprogramoutputwillappearlikethis:
Figure428.OutputofProgram:
YCL_CH04_17_DESCRIBE_FIELD
YoucancrosschecktheoutputlengthofdomainNETWRas21.The
lengthofTYPESTRINGisappearingas8,whichistheinitialallocation
ofRAMtoit.
ThelengthforTYPESC,D,N,andTcanbedeterminedeitherin
charactersorbytes.Soyoucangiveeitheroftheoptions:IN
CHARACTERMODE/INBYTEMODE.With16bitUnicodeinoperation
(2bytes),thelengthreturnedinbyteswillbetwicethelengthreturnedin
characters.
FortheTYPESotherthanC,D,N,andT,thelengthwillbereturnedin
bytesandhencetheoptionINBYTEMODEisacceptablesyntactically.
Duringthecompilation,theABAPcompilercheckstheDDICdataobject
referencesandalsodeterminestheTYPEandsyntacticallyrejectsthe
INCHARACTERMODEoptioniftheTYPESareotherthanC,D,N,and
T.Thatisthereasonyouhavecommentedonthelineswherethissyntax
errorishighlighted.Youwillbeabletotacklethissyntaxerrorafter
learningsubroutinesintheforthcomingChapter7:Modularization.
Conclusion
YouhavelearnedthebasicelementsoftheABAPlanguage.Afew
programs,mostlyinvolvingstringoperations,werecoded.These
programsweresmallandsimple.Youwerealsointroducedtothe
WRITEstatementusedforgettingoutput.Thiswasusedtovisuallysee
theresultofouroperationsintheprograms.
Fromthenextchapteronward,youaregoingtoretrievedatafrom
databasetables.InbusinessapplicationsnotablySAPdataretrieval
fromdatabasetablesformsamajortask.
PREV
NEXT
Recommended
/ Queue
/ Recent / Topics
/ Tutorials /Settings
/ Blog / Feedback / Sign OutChapter 5: WRITE Statement (Classical Reporting)
Chapter 3: ABAP
Dictionary/Data
Dictionary/DDIC
2
2016 Safari.
Terms of Service / Privacy Policy
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch04.xhtml
34/34