You are on page 1of 44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

SAP ABAP: Hands-On Test Projects with Business Scenarios

Recent

Topics
Tutorials

NEXT

PREV

Chapter 5: WRITE Statement (Classical Reporting)

CHAPTER6

ChapterHighlights
7: Modularization

Settings
Feedback

InternalTables

Sign Out

Internaltablesarecomplexdataobjectsdistinctfromelementarydata
objectsinanABAPprogram.Theearliercomplexdataobjectscovered
werestructures.Aninternaltableiswhatiscalledastructuredarrayin
otherplatforms.Likeitsnamesuggests,itcanstoremultiplerowsof
data,anditcangrowandshrinkdynamicallyduringprogramexecution.
Itexistsonlyduringtheprogramsexecution.Aninternaltablecanbea
structuredarrayorasimplearray.Mostoften,itwouldbeastructured

Settings
10 days left in your trial. Subscribe.

Feedback

array.IntheSAPR/3clientserverarchitecture,datawillberetrieved
andloadedfromthedatabasetablesinlargechunksintotheinternal
tables(applicationserverRAM)andprocessedfromtheseinternal

Sign Out

tables.Thedatabaseservershouldnotbeburdenedwithapplication
processing.Thedatabaseservicesaretoberequisitionedselectivelyand
infrequentlyfordatamaintenance,management,andretrieval.Thatis
whyretrievaloflargechunksofdataispreferredinsteadoffrequent
retrievalofsmallamountsofdataallofthisisforbetterperformance.
Theinternaltablesfitintothisscenario.
Theinternaltablescanbedeclaredinmanydifferentways,andthe
numberofoperationsyoucanperformontheinternaltablesarealot
morecomparedtothestructuredarraysoftheotherplatforms.
Theinternaltablesaresometimesreferredtoasjusttables,butthis
Enjoy Safari? Subscribe Today

shouldnotcauseconfusion.Thecontextwillmakeitapparentthatwhen
thewordtableisused,thereferenceistoaninternaltable.
Inthischapter,theinternaltabletypesanddeclarationsarecovered.
Youwilllearnthedifferentwaystofillorloadinternaltables,howto
processinternaltabledatasequentially,andhowtoretrievearow
randomly.Youwillfurtherlearnhowtochangeorupdateexistingdatain
internaltablesandhowtodeletedataininternaltables.Theuseof
internaltablestogenerateamultilevelsummaryisexplained.The
chapterconcludeswithstatementstoderiveinternaltableattributesand
initializeinternaltables.
YouwillalsoknowhowtocreateandusetheDDICobjectsstructureand
Tabletype.
DDICObject:Structure
YouwillbecreatingaDDICstructurefirst.Itsusageissubsequently
requiredinthischapter.
YoucanmaintainDDICstructurethroughthethirdradiobuttononthe
SE11ABAPDictionaryopeningscreen:thesameradiobuttonyouusedto
maintaindataelements.AthirdDDICobjecttheTabletypeisalso
maintainedthroughthisradiobutton.ADDICstructureorsimplya
structure,likeitsnamesuggests,isabaredefinition.UnliketheDDIC
tabledefinition,thisdoesnotcreateanydefinitioninthedatabase
metadataonactivation.Soitcannotbepopulatedwithanydata.
ItservesthepurposeofbeingusedinDDICtabledefinitionsandother
DDICstructures,Tabletypedefinitions,andreferencedinABAP
programs.
Youcancheckthisout(DDICstructureusedinDDICtabledefinitions)in
thecustomerprimarytableKNA1.Whenyouscrolldownthefieldsinthe
KNA1table,youwillseethe.INCLUDEasafieldnameunderthe
columnFieldandSI_KNA1underthecolumnDataelement(double

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

1/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

clickonSI_KNA1andviewthisstructure).Thisisaninstanceoffields
fromaDDICstructureincorporatedinaDDICtabledefinition.The
incorporatedfieldsappearinabluecoloragainstthelocalfields(fields
definedinthetabledefinition)appearinginblack.Throughthisconcept
ofincorporatingstructurefieldsintoatabledefinition,SAPcustomers
canincorporatetheirownfieldsintoSAPdeliveredtables.WhenSAP
customersincorporatesuchfieldsintoSAPdeliveredtables,itisan
instanceofenhancement(i.e.,enhancementofSAPdeliveredobjects).
Liketables,mostSAPdeliveredobjectsintheABAPWorkbench
environmentcanbeenhanced.However,enhancementsarenot
coveredinthisbook.
DDICstructuredefinitionsareassignedtoDDICTabletype(internal
table)definitions.ThiswillbeapparentintheforthcomingtopicCreate
DDICInternalTableTypeofthischapter.
ADDICstructuredefinitionisverysimilartoaDDICtabledefinition.A
DDICstructurehasnoDeliveryandMaintenancetab,andnoTechnical
Settingsbuttonthesetworelatetodata.TheDDICstructuredefinition
canhavesearchhelpattachedtofields,haveforeignkeyfields,and
referencetableandreferencefieldcolumnsforcurrencyquantityfields.
Apartfrombeingusedinothertables,structuredefinitionsandTable
typedefinitions,aDDICstructurecanbereferencedtodeclareinternal
dataobjectsintheABAPprograms.TheSAPfunctionalmoduleentity
datanormallyresidesinmultipletables.Thefieldsofthemultipletables
canbeincludedinonecompositeDDICstructuredefinition.This
compositestructurecanbeusedtodeclarestructureddatainABAP
programs.Thisfacilitatesscreenprogramminginvolvingmultipletables
andmultiplescreens.
LetscreateaDDICstructureYCL_CH06_CUST_STRUconsistingofthe
followingcustomerdatafields:

TheenteredfieldswiththedataelementswillappearasshowninFigure
61.

Figure61.DDICObjectStructureYCL_CH06_CUST_STRU

Youcanusesomeotherfieldnames,butitisgoodpracticetosticktothe
SAPstandardnames.Thestandarddataelementshavebeenassignedto
thesestructurefields.
SetEnhancementCategorytoCannotBeEnhanced,performa
consistencycheck,andactivatethestructure.Youhavenowcreateda
DDICstructure.
InternalTablesDeclarations
Youhavetwobroadwaysofdeclaringinternaltables.First,theway
internaltablesweredeclareduntilSAPR/3version3.X(i.e.,version3
andallitssubversions)andthewayinternaltablesaredeclaredfrom
SAPR/3version4.0onward.Youwillcalltheinternaltabledeclarations
inthe3.Xmodeand4.xmodeofdeclaration.Youareadvisedtousethe
4.Xmodeofinternaltabledeclaration.Infact,withintheABAPOOPS
environment(classdefinitionsandimplementations),the3.Xmodeof
internaltabledeclarationisnotsupported.The3.Xmodeofinternal
tabledeclarationwillbeintroducedfirst,sothatyouareexposedtoit.
Youwillthenswitchovertothe4.Xmodeofdeclarationandusethe4.X
modeofdeclarationthroughouttherestofthebook.
InternalTables3.XModeofDeclarations
Theinternaltablesdeclaredin3.Xmodearecalledthestandardtables.
Whatfollowsaredifferentwaysofdeclaringinternaltablesin3.xmode.
Theromannumeralssignifythis.
DeclaringtheInternalTableandStructureTogether
Thesimplestwayofdeclaringaninternaltablein3.Xmode:

DATA:BEGINOF<internaltablename>OCCURS<number>,
<field1>.........,

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

2/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

<field2>.........,
......................
ENDOF<internaltablename>.

OCCURS<number>:Theabovedeclarationissomewhatlikethewayyou
declaredstructuresinyourprogramsuntilnow,exceptthatthereisthe
additionOCCURS<number>.Thisadditioniswhatmakesitaninternal
table.ThewordOCCURSisareservedkeyword.The<number>canbe
anysmallintegervalue,evenzero.The<number>willdeterminethe
initialRAMallocationwhentheprogramstartsexecution.Theinternal
table,ofcourse,growsdynamically.The<number>alsodeterminesthe
incrementalblockofRAMallocatedeverytimetheinternaltablegrows.
TwoDataObjectswiththeSameName:Thedeclarationmadeabove
createstwodataobjectsofthesamename(i)astructureand(ii)an
internaltable.Withtwodataobjectswiththesamename,theissueof
ambiguityarises.Whenareferenceismadewiththisname,howdoyou
knowwhetherthisisareferencetotheinternaltabledataobjectortothe
structureddataobject?Mostofthetime,thesystemwillresolvethis
ambiguitybycontext(i.e.,certainABAPstatementsoperateonlyonthe
internaltablewhilecertainstatementsoperateonlyonthestructure).
Whenstatementsarecommontobothtypesofdataobjects,youshould
addbrackets([])afterthedataobjectnameifyoumeantorefertothe
internaltabledataobject.Anamewithoutthebracketsreferstothe
structure.
Example:

DATA:BEGINOFCUSTOMER_TABOCCURS5,
KUNNRTYPEKNA1KUNNR,
NAME1TYPEKNA1NAME1,
ENDOFCUSTOMER_TAB.

Thisdeclarationcreatesaninternaltableandastructureusingthesame
name:CUSTOMER_TAB.
YouDeclareanInternalTablebyReferringtoaLocal/Global
StructuredTYPEorLocal/GlobalStructure
(aglobalstructureincludesadatabasetableandallkindsofviews).

DATA<internaltablename>{TYPE|LIKE}<structurename>OCCURS<number>.
<structurename>iseither

1. AstructuredTYPEdeclaredlocallywiththeTYPESkeyword.The
keywordTYPEnotLIKEshouldbeusedwhenreferringtoit.
Example:
*Internaltabledeclaredbyreferringto
*alocalstructureTYPE
TYPES:BEGINOFCUSTOMER_STRU_TYPE,
KUNNRTYPEKNA1KUNNR,
NAME1TYPEKNA1NAME1,
ENDOFCUSTOMER_STRU_TYPE.
DATA:CUSTOMER_TABTYPECUSTOMER_STRU_TYPEOCCURS5.

2. AstructuredTYPEdeclaredintheDDICobjectTypeGroup.The
keywordTYPEnotLIKEshouldbeusedwhenreferringtoit.
Example:

*Internaltabledeclaredbyreferringto
*aDDICstructureTYPEinTypeGroup
TYPEPOOLSYCLG1.
DATA:CUSTOMER_TABTYPEYCLG1_CUSTOMER_TYPEOCCURS5.

ATYPEYCLG1_CUSTOMER_TYPEhasbeencreatedintheType
GroupYCLG1asshowninFigure62.

Figure62.{TYPEYCLG1_CUSTOMER_TYPEinType
GroupYCLG1[highlighted]

3. Astructuredeclaredlocally.ThekeywordLIKE,notTYPE,should
beusedwhenreferringtoit.
Example:

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

3/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

*Internaltabledeclaredbyreferringto
*alocalstructure
DATA:BEGINOFCUSTOMER_STRU,
KUNNRTYPEKNA1KUNNR,
NAME1TYPEKNA1NAME1,
ENDOFCUSTOMER_STRU.
DATA:CUSTOMER_TABLIKECUSTOMER_STRUOCCURS5.

NextletslookatastructurecreatedinaDDICdatatypeora
databasetableoraview.ThekeywordsTYPEorLIKEcanbeused
whenreferringtoit.
Examples:
*Internaltabledeclaredbyreferringto
*aDDICstructure
DATA:CUSTOMER_TABTYPEYCL_CH06_CUST_STRUOCCURS5.
ADDICtypestructureYCL_CH06_CUST_STRUisshowninFigure63.
*Internaltabledeclaredbyreferringto
*aDDICtabledefinition
DATA:CUSTOMER_TABTYPEKNA1OCCURS5.
*Internaltabledeclaredbyreferringto
*aDDICview
DATA:CUSTOMER_TABTYPEYCL_CH05_VBRKKNAOCCURS5.

Figure63.DDICStructureYCL_CH06_CUST_STRU

DeclaringBothanInternalTableandaStructurebyReferringto
aStructuredLocal/GlobalTYPEorLocal/GlobalStructure
(globalstructureincludesadatabasetableandallkindsofviews)
AllconsiderationsofIIapplyhereexceptthatyouarecreatingtwodata
objectsofthesamename(i)aninternaltableand(ii)astructure:

DATA<internaltablename>{TYPE|LIKE}<structurename>OCCURS<number>
WITHHEADERLINE.

WITHHEADERLINEisareservedkeyphrase.Theadditionofthis
phrasecreatesastructure.AdeclarationwithoutthisphraseasinII
createsonlyaninternaltable.Theambiguityissueisresolvedinthe
samewayasinI.
Examples:
YoucouldaddthephraseWITHHEADERLINEtotheexamplesofIIand
deriveexamplesforthismodeofinternaltabledeclaration.
DeclaringNonstructuredInternalTables(SimpleArrays)
Thenonstructuredinternaltablescanbedeclaredbyreferringto
elementarydatatype(local/global),dataobject(local/global),anddata
element.
Examples:

*nonstructureinternaltablereferringtolocalTYPE
TYPESSTR_TYPE(10)TYPEC.
DATASTR_TABTYPESTR_TYPEOCCURS5WITHHEADERLINE.
*nonstructureInternaltabledeclaredbyreferringto
*aDDICstructureTYPEfieldinTypeGroup
TYPEPOOLSYCLG1.
DATA:STR_TABTYPEYCLG1_CUSTOMER_TYPEKUNNROCCURS5.
*nonstructureinternaltablereferringtolocaldataobject
DATA:STRNG(10)TYPEC,
STR_TABLIKESTRNGOCCURS5.
*nonstructureinternaltablereferringtoglobaldataobject
DATA:STR_TABLIKEKNA1KUNNROCCURS5WITHHEADERLINE.
*nonstructureinternaltablereferringtoDDICdataelement
DATA:STR_TABTYPEKUNNROCCURS5."KUNNRisdataelement

DeclaringaStructurebyReferringtoanInternalTable
Example:

*astructuredeclarationbyreferringto
*aninternaltable

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

4/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

TYPES:BEGINOFCUSTOMER_STRU_TYPE,
KUNNRTYPEKNA1KUNNR,
NAME1TYPEKNA1NAME1,
ENDOFCUSTOMER_STRU_TYPE.
DATA:CUSTOMER_TABTYPECUSTOMER_STRU_TYPEOCCURS5,
CUSTOMER_STRULIKELINEOFCUSTOMER_TAB.

CUSTOMER_STRUisdeclaredbyreferringtotheinternaltable
CUSTOMER_TAB.ThephraseLIKELINEOFheremeansLIKEthe
structureofinternaltable.Thedeclaredstructurewillhavethesame
fieldsastheinternaltablestructure.
Thestructuresusedwithinternaltablesareoftenreferredtoaswork
areas.Astructurewiththesamenameasaninternaltableisoften
referredtoasaheaderline.
HandsOnExercise:ListofBillingDocumentsofaSpecified
CompanyCode
YouwillrepeattheexerciseofChapter5thatusedthe
SELECT...ENDSELECTloopwiththeviewYCL_CH05_VBRKKNA.This
viewcontainsfieldsfromthetablesKNA1andVBRK.Now,youwillload
datefromthisviewintoaninternaltableandprocessfromtheinternal
table.
YouwilldeclareaninternaltablewiththenotationBEGIN
OF...OCCURS...ENDOF....(Internaltableandstructurearecreated
withthisdeclaration).Youwillloadthisinternaltablewithdatafromthe
viewwithavariationoftheSELECTstatement.Asyouarenotfetching
onerowatatimefromtheview,thiswillnotbealoopingrepetitive
constructoftheSELECTstatement.
Oncetheinternaltableisloadedwithdata,youhavetofetchdatarowby
rowfromtheinternaltableintoastructureandoutputitfromstructure
fieldsusingtheWRITEstatement.
Theprocessofloadinganinternaltablefromadatabasetable/viewand
processingitrowbyrowfromtheinternaltableintoastructureis
representedinFigure64.

Figure64.LoadInternalTablefromDatabaseTable/View&
ProcessinLOOP..ENDLOOPConstruct

AninternaltableconstructLOOPAT...ENDLOOPsomewhataparallelto
theSELECT...ENDSELECTisavailableforarowbyrowprocessing.A
simplesyntaxofthisinternaltableconstructislike:

LOOPAT<internaltablename>into<structurename>.
<statementblock>
ENDLOOP.

YouroutputbodywillhavethelayoutinTable61(fromChapter5).
Table61.OutputBodyLayout

Youhavedeclaredtheinternaltablewithonlytherequiredfields:thatis,
thefieldsappearingintheoutputandthefieldKURRF(exchangerate)to
convertallamountstotheoperatingcurrencyofthecompanycode.You
dontneedthefieldBUKRS(companycode)fromtheview,thoughyouare
specifyingitintheWHEREconditionoftheSELECTstatement.
ThedataistransferredfromviewtointernaltablewiththeSELECT
statementvariation.YouareusingthekeyphraseINTOTABLEand
specifyingtheinternaltablenamenext.
TheLOOPATstatementfetchesonerowatatimefromtheinternaltable

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

5/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

intothestructurestartingfromthefirstrow,thenthesecondrow
overwritingtheexistingcontentsofthestructure,andsoonuntilallthe
rowshavebeenfetchedfromtheinternaltable.Whenallrowsare
fetched,thecontrolwillfalltothestatementnexttotheENDLOOP
statementifany,orelseitwillexittheprogram.Therearefew
variationsintheLOOPATstatement.YoucanspecifyaWHERE
conditionandyoucanspecifyastartingrowtofetchfromandanending
rowtoconcludethefetching.Youneednotfetcharowintoastructureas
youcandirectlyrefertothedatainarow.
Whentheinternaltablenameandthedestinationstructurename
(followingtheINTOkeyword)arethesame,theINTO
<destination/structurename>canbedroppedandthedestinationis
implicit.Insideclassesthisimplicitnessisdisallowed.Anditisagood
practicetomentionthedestinationexplicitly.
TheorderofthefieldsintheSELECTstatementandtheinternaltable
structuremustbeidentical.Theinternaltablestructuremustnotcontain
anyotherfields.Eachofthefieldsinthetablestructuremustbeidentical
tothecorrespondingfieldintheSELECTstatement<result>intermsof
type,length,etc.
YouwereusinginyourChapter5programthesystemfieldSYDBCNTin
theSELECT...ENDSELECTloop.Thiscontainedthecurrentnumberof
therowofdatafetched.Youcannolongerusethis.Youarenow
processingrowbyrowfromaninternaltableinaLOOP...ENDLOOP
construct.Inyourpresentprogram,youareloadingtheinternaltable
fromtheviewinonego.ThesystemfieldSYDBCNTafterthe
SELECT...INTOTABLE...hasbeenexecutedwillcontainthetotal
numberofrowsloadedintotheinternaltable.
Youneedaserialnumberforthelist.Youcanalwaysdeclareanumeric
dataobject(typeI,N,P)andincrementitbeforetheWRITEstatement
andoutputit,butyouhaveasystemfieldrelatingtointernaltable
operationsparalleltotheSYDBCNT.ThisisthesystemfieldSYTABIX.
WithintheLOOP...ENDLOOPconstruct,itcontainsthenumberofthe
rowfetched.Soyoucanusethistooutputtheserialnumber.Thesystem
fieldSYTABIXisoftypeI.
CopyandactivatethetextsymbolsfromtheChapter5programintothe
currentprogramusingthetransactioncodeSE32.
TherestofthecodeissameasinChapter5.Thesourcecodefor
generatingtheBillingDocumentlistusinganinternaltable:

REPORTYCL_CH06_ITAB01LINESIZE135LINECOUNT60
NOSTANDARDPAGEHEADING.
*********************************************************************
*ListofBillingDocumentsofaSpecifiedCompanyCodewithTotal**
*********************************************************************
*******************************************************************
*declareinternaltablein3.Xmode:BEGINOF<itab>OCCURS<n>.**
*..**
*ENDOF,itab>**
***
*PARAMETERSCCODETYPEVBRKBUKRSVALUECHECKDEFAULT3000**
*toselectcompanycode**
***
*getBUTXTWAERSfromT001SELECTSINGLEetc.**
***
*loadtheinternaltablefromtheviewYCL_CH05_VBRKKNA**
*withSELECT<fields>fromYCL_CH05_VBRKKNAINTOTABLE<itab>**
*WHEREBUKRS=CCODE.**
***
*setLOOPAT<itab>into<itab>.**
*calculateamountinoperatingcurrencyofchosenCCODE**
*WRITE...**
*buildtotal**
*ENDLOOP.**
***
*outputtotal**
***
*******************************************************************
TABLES:T001."localstructurewithallfieldsofT001
DATA:BEGINOFBILL_DOCS_TABOCCURS5,
VBELNTYPEYCL_CH05_VBRKKNAVBELN,
FKDATTYPEYCL_CH05_VBRKKNAFKDAT,
KUNNRTYPEYCL_CH05_VBRKKNAKUNNR,
NAME1TYPEYCL_CH05_VBRKKNANAME1,
ORT01TYPEYCL_CH05_VBRKKNAORT01,
NETWRTYPEYCL_CH05_VBRKKNANETWR,
KURRFTYPEYCL_CH05_VBRKKNAKURRF,
ENDOFBILL_DOCS_TAB,
STRNGTYPESTRING,
TOTALTYPEVBRKNETWR.
PARAMETERSCCODETYPEVBRKBUKRSDEFAULT3000VALUECHECK.
"theclauseVALUECHECKwillcheckvalues
"intheprimarytableofthisforeignkeyfield
********************************************************************
TOPOFPAGE.
WRITE:/5STRNG,129(3)SYPAGNO."STRNGreferCONCATENATEstatementin
"STARTOFSELECTION
SKIP1.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

6/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

WRITE:/5(127)SYULINE.
WRITE:/5TEXT003,11TEXT004,22TEXT005,33TEXT006,46TEXT007,
83TEXT008,126TEXT009.
WRITE:/6TEXT010,35TEXT011.
WRITE:/5(127)SYULINE.
********************************************************************
STARTOFSELECTION.
SELECTSINGLE*FROMT001WHEREBUKRS=CCODE."fetchesasinglerow,no
"loopconstructSELECT
"ENDSELECT
CONCATENATETEXT001CCODE'/'T001BUTXTTEXT002T001WAERSINTOSTRNG.
SELECTVBELNFKDATKUNNRNAME1ORT01NETWRKURRFFROM
YCL_CH05_VBRKKNAINTO"dumpsfilteredfulldatafrom
TABLEBILL_DOCS_TAB"viewintotheinternaltable
WHEREBUKRS=CCODE.
********************************************************************
LOOPATBILL_DOCS_TABINTOBILL_DOCS_TAB.
BILL_DOCS_TABNETWR=BILL_DOCS_TABNETWR*BILL_DOCS_TABKURRF.
WRITE:/5(5)SYTABIX,BILL_DOCS_TABVBELN,BILL_DOCS_TABFKDAT,
BILL_DOCS_TABKUNNR,BILL_DOCS_TABNAME1,
BILL_DOCS_TABORT01,(17)BILL_DOCS_TABNETWR.
TOTAL=TOTAL+BILL_DOCS_TABNETWR.
ENDLOOP.
********************************
ENDOFSELECTION.
SKIP1.
WRITE:/(17)TOTALUNDERBILL_DOCS_TABNETWR."thefieldTOTALwill
"beoutput
"UNDERNETWR.

TheoutputswilllooklikeFigures65and66.

Figure65.OutputofProgramYCL_CH06_ITAB01

Figure66.OutputofProgramYCL_CH06_ITAB01Grand
Total

HandsOnExercise:CustomerCodeWiseListofBilling
DocumentsofaSpecifiedCompanyCodewithTotalsforEvery
CustomerandaGrandTotal
Letahandsonexercisebeperformedwithadifferentmodeofinternal
tabledeclaration.Theprecedinghandsonexerciseisbeingtweakeda
bit.Thishandsonexercisewilluseasinput,thesamedatabaseviewas
theprecedingone.
Youwillagainproduceabillingdocumentlist.Butthebillingdocuments
listwillbeordered.Allbusinessapplicationlistsorreportsareordered:
dataisneverpresentedinarandomfashion.Letthebillingdocument
listbeproducedcustomerwise,soallthebillingdocumentsofacustomer
willbebunchedtogether.Youwillimplementthisbyoperatingthesort
statementontheinternaltable.
Youareaddingtwomorefields(ofVBRKtable)totheoutputlist.The
additionalfieldswillbe:
VBRKBSTNK_VFCustomerPurchaseOrderNo
VBRKMWSBKTaxAmountinDoc.Currency

YouwillalsooutputtotalsoffieldsNETWRandMWSBKforeach

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

7/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

customer,andfinallygrandtotalsforthesefields.
Youcaneithercreateanewdatabaseviewwiththeseadditionalfields
incorporatedoraddthesetwofieldstotheexistingdatabaseview
YCL_CH05_VBRKKNA.Sinceyouarebuildingtotalstooutputthem,you
willconvertthebillingdocumentamounts(netvalue&tax)intothe
operatingcurrencyofthecompanycode.Aroughlayoutofyouroutput:

Studythislayoutcarefully.Youhaveplannedtohaveallthebilling
documentsofacustomerbunchedintheoutput.Soyouneednotoutput
customerinfointheregularoutputbodyascolumnswithcolumn
headings:thesamevalueswillrepeatagainandagain.Thecustomer
information(KUNNR,NAME1)isplannedtobeoutputasasubheading.
Thedataintheinternaltableissortedinascendingorderofthefield
KUNNR.Youshouldbuildthelogicinawaythatwhenacustomer
changes,outputthetotalforthepreviouscustomer,nextoutputthecode
andnameofthecurrentcustomerthenthebillingdocumentsforthe
currentcustomerwillfollowasthelistbody.
Theserialnumberisnotarunningserialnumberitisaserialnumberof
abillingdocumentforacustomer.Foreverycustomer,itwillcommence
from1.HenceavariableCNT(typeI)isdeclared.ThevariableCNTis
incrementedbeforetheWRITEstatementofabillingdocumentand
initializedbeforeoutputforthenextcustomerstarts(SYTABIXwillnot
servethispresentcontext).
Thelistbodylayout:
Table62.OutputBodyLayout

Create,performsyntaxcheckandactivatetheprogram.Createand
activatethetextsymbols.Thesourcecodetogeneratetheoutput:
REPORTYCL_CH06_ITAB02LINESIZE105LINECOUNT60
NOSTANDARDPAGEHEADING.
************************************************************************
*CustomerWiseListofBillingDocumentsofaSpecifiedCompanyCode**
************************************************************************
*******************************************************************
*declareinternaltablein3.Xmode:**
*<itab>TYPE<databaseviewname>OCCURS<n>.**
***
*declarestructure<structurename>TYPE<databaseviewname>.**
***
*PARAMETERSCCODETYPEVBRKBUKRSVALUECHECKDEFAULT3000**
*toselectcompanycode**
***
*getBUTXTWAERSfromT001SELECTSINGLEetc.**
***
*loadtheinternaltablefromtheviewYCL_CH05_VBRKKNA**
*withSELECT*fromYCL_CH05_VBRKKNAINTOTABLE<itab>**
*WHEREBUKRS=CCODE.**
***
*SORT<itab>BYKUNNRASCENDING**
***
*setLOOPAT<itab>into<structurename>.**
***
*checkforcustomerchange.ifchangeoutputtotalsfor**
*previouscustomer,outputcurrentcustomerinfo**
***
*calculateamountinoperatingcurrencyofchosenCCODE**
***
*WRITE...**
***
*buildcustomertotals,grandtotals**
***
*ENDLOOP.**
***
*outputcustomertotal,grandtotal**
***
*******************************************************************
TABLES:T001.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

8/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

DATA:BILL_DOCS_TABTYPEYCL_CH05_VBRKKNAOCCURS5,"referencetoview
BILL_DOCS_STRUTYPEYCL_CH05_VBRKKNA,"referencetoview
CNTTYPEI,"countofbillingdocsofacustomer
PREV_KUNNRTYPEKNA1KUNNR,"previousKUNNR
CTOTALTYPEVBRKNETWR,"customernetvaluetotal
CTAX_TOTALTYPEVBRKMWSBK,"customertaxtotal
GTOTALTYPEVBRKNETWR,"grandnetvaluetotal
GTAX_TOTALTYPEVBRKMWSBK."grandtaxtotal
PARAMETERSCCODETYPEVBRKBUKRSDEFAULT3000VALUECHECK.
********************************************************************
TOPOFPAGE.
WRITE:/5TEXT001,CCODENOGAP,'/'NOGAP,T001BUTXT,
93TEXT003,98(3)SYPAGNO.
WRITE:/33TEXT002,T001WAERS.
SKIP1.
WRITE:/5(96)SYULINE.
WRITE:/5TEXT004,11TEXT005,22TEXT006,33TEXT007,
79TEXT008,91TEXT009.
WRITE:/6TEXT010,34TEXT011.
WRITE:/5(96)SYULINE.
********************************************************************
STARTOFSELECTION.
SELECTSINGLE*FROMT001WHEREBUKRS=CCODE."fetchesasinglerow,no
"loopconstructSELECT
"ENDSELECT
SELECT*FROM
YCL_CH05_VBRKKNAINTO"dumpsfilteredfulldatafrom
TABLEBILL_DOCS_TAB"viewintotheinternaltable
WHEREBUKRS=CCODE.
SORTBILL_DOCS_TABBYKUNNRASCENDING."SORTtableonthefieldKUNNR
"inASCENDINGorder
********************************************************************
LOOPATBILL_DOCS_TABINTOBILL_DOCS_STRU.
IFBILL_DOCS_STRUKUNNR<>PREV_KUNNR.
IFCNT>1ANDSYTABIX>1.
FORMATINVERSECOLORCOL_GROUP."customertotaldifferentcolor
WRITE:/(17)CTOTALUNDERBILL_DOCS_STRUNETWR,
(15)CTAX_TOTALUNDERBILL_DOCS_STRUMWSBK.
FORMATRESET."restoredefaultcolors
ENDIF.
IFSYTABIX>1.
SKIP.
CTOTAL=0.
CTAX_TOTAL=0.
CNT=0.
ENDIF.
FORMATINVERSECOLORCOL_POSITIVE."customerinfodifferentcolor
WRITE:/5TEXT011,BILL_DOCS_STRUKUNNRUSINGNOEDITMASK,
BILL_DOCS_STRUNAME1.
FORMATRESET."restoredefaultcolors
ENDIF.
BILL_DOCS_STRUNETWR=BILL_DOCS_STRUNETWR*BILL_DOCS_STRUKURRF.
BILL_DOCS_STRUMWSBK=BILL_DOCS_STRUMWSBK*BILL_DOCS_STRUKURRF.
CNT=CNT+1.
WRITE:/5(5)CNT,BILL_DOCS_STRUVBELN,BILL_DOCS_STRUFKDAT,
BILL_DOCS_STRUBSTNK_VF,(17)BILL_DOCS_STRUNETWR,
(15)BILL_DOCS_STRUMWSBK.
GTOTAL=GTOTAL+BILL_DOCS_STRUNETWR.
CTOTAL=CTOTAL+BILL_DOCS_STRUNETWR.
GTAX_TOTAL=GTAX_TOTAL+BILL_DOCS_STRUMWSBK.
CTAX_TOTAL=CTAX_TOTAL+BILL_DOCS_STRUMWSBK.
PREV_KUNNR=BILL_DOCS_STRUKUNNR.
ENDLOOP.
********************************
ENDOFSELECTION.
IFCNT>1.
FORMATINVERSECOLORCOL_GROUP."customertotaldifferentcolor
WRITE:/(17)CTOTALUNDERBILL_DOCS_STRUNETWR,
(15)CTAX_TOTALUNDERBILL_DOCS_STRUMWSBK.
ENDIF.
SKIP1.
FORMATINVERSECOLORCOL_TOTAL."grandtotaldifferentcolor
WRITE:/(17)GTOTALUNDERBILL_DOCS_STRUNETWR,
(15)GTAX_TOTALUNDERBILL_DOCS_STRUMWSBK.

Thecustomerinfo(BILLS_STRUKUNNR,BILLS_STRUNAME1)
areoutputinadifferentcolor(COL_POSITIVE).
Thecustomerwisetotals(CTOTAL,CTAX_TOTAL)areoutputina
differentcolor(COL_GROUP).

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

9/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

Thegrandtotals(GTOTAL,GTAX_TOTAL)areoutputina
differentcolor(COL_TOTAL).
Fortherestoftheinfo,youareusingthedefaultcolor,hencethe
FORMATRESETstatement.
Ifacustomerhasonlyonebillingdocument,thatis,CNT=1,customer
wisetotalsarenotoutput.Therestofthelogicshouldbeokay!Theoutput
willappearlikeFigures67and68.

Figure67.OutputofProgramYCL_CH06_ITAB02

Figure68.OutputofProgramYCL_CH06_ITAB02Grand
Totals

InternalTableDeclarationsContinued
Youwereintroducedtointernaltabledeclarationsin3.xmode.You
performedhandsonexercisesusinginternaltablesdeclaredin3.x
mode.Youwillnowbeintroducedtodeclarationofinternaltablesin4.x
mode.Inallthesubsequentchapters,youwilldeclareinternaltablesin
4.xmode.
InternalTables4.XModeofDeclarations
The3.Xmodeofinternaltabledeclarationssupportedonlyonetypeof
internaltable:thestandardtable.Theinternaltablesyouusedinyour
twohandonexerciseswerestandardtables.
Thestandardtableshavestandardkeys.Thestandardkeyiscomposedof
allthenonnumericfieldsoftheinternaltablestructure(elementary
typesC,D,N,andT).Fortheinternaltableyoudeclaredinourfirst
handsonexerciseprogram:

DATA:BEGINOFBILL_DOCS_TABOCCURS5,
VBELNTYPEYCL_CH05_VBRKKNAVBELN,
FKDATTYPEYCL_CH05_VBRKKNAFKDAT,
KUNNRTYPEYCL_CH05_VBRKKNAKUNNR,
NAME1TYPEYCL_CH05_VBRKKNANAME1,
ORT01TYPEYCL_CH05_VBRKKNAORT01,
NETWRTYPEYCL_CH05_VBRKKNANETWR,
KURRFTYPEYCL_CH05_VBRKKNAKURRF,
ENDOFBILL_DOCS_TAB,

ThestandardkeyofthisinternaltableisVBELN,FKDAT,KUNNR,
NAME1,andORT01.
The4.Xmodeofinternaltabledeclarationssupportthestandardtables
aswellastwoadditionalinternaltabletypes:thesortedtablesandthe
hashedtables.
InternalTablesFeatures,Attributes
Key
Astandardtablecanhavethedefault/standardkey(allfieldsofTYPESC,
D,N,andT)oradefinedkey.Thekeyfieldsofadefinedkeyare
specifiedwiththetabledeclaration.Astandardtablesupportsonlya
NONUNIQUEdefinedkey.Rowswithduplicatekeyvaluescanexistin
standardtables.
Sortedandhashedtablescanhaveonlydefinedkeys.Thekeyfieldsarea
mandatorypartoftabledeclarationforsortedandhashedtables.
AsortedtablecanbedeclaredwithUNIQUEKEYorwithNONUNIQUE
KEY.IfasortedtablehasbeendeclaredwithUNIQUEKEY,rowswith

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

10/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

duplicatekeyvaluescannotexist.IfasortedtableisdeclaredwithNON
UNIQUEKEY,rowswithduplicatekeyvaluescanexist.
AhashedtablecanbedeclaredonlywithUNIQUEKEY.Rowswith
duplicatekeyvaluescannotexistinthehashedinternaltable.
SearchMethod
Thereisaninternaltablestatement
READTABLE<internaltablename>WITHTABLEKEY<k1>=<f1>
...INTO<structurename>.

Thisstatementsearchesforarowonthebasisofthekeyfieldvalues
providedthrough<k1>=<f1>.Iflocated,itfetchestherowintothe
<structurename>.
Inthestandardtables,thesearchingfortherowwiththeprovidedkey
fieldvaluesisbydefaultalinearsearch.Thesearchwillcommencefrom
thefirstrowandwillcontinueuntilarowislocatedwithprovidedkey
fieldvaluesorthesearchconcludeswiththelastrowwithoutlocatinga
rowwiththeprovidedkeyfieldvalues.Theaccesstimeinlinearsearchis
dependentonthenumberofrowsintheinternaltable.Forthestandard
tables,youcanspecifyabinarysearchmethodwiththeREADstatement,
butitisyourresponsibilitytoensurethatthetableissortedinascending
orderofkeyfieldsspecifiedintheREADstatement.Iftheinternaltable
isnotordered,thesystemwillnotcheckandalertitwillprovide
erroneousresults.Theaccesstimeinbinarysearchislogarithmically
proportionallytothenumberofrowsintheinternaltable.
Inthesortedtables,theREAD...statementusesthebinarysearchmethod
tolocatearowwiththeprovidedkeyfields.Theaccesstimeinbinary
searchislogarithmicallyproportionaltothenumberofrowsinthe
internaltable.
Inhashedtables,theREAD...statementusesahashedalgorithmmethod
tolocatearowwiththeprovidedkeyfields.Theaccesstimeinhashed
tablesisindependentofthenumberofrowsintheinternaltable.
Sort
AstandardtablecansortedanynumberoftimeswiththeSORT
statement.
YoucannotperformSORTonasortedtable.Whendataisloadedintothe
sortedtablewiththeSELECTstatementorwiththeINSERTstatement,
therowsaremaintainedintheascendingorderofthekeyfields
automatically.
Ahashedtablecanbesorted,butitdoesnotmakesense.Yousortdata
whenyouwanttoprocessdatasequentiallyorseriallywiththedata
appearinginorderedmanner.Thehashedtableisconceivedforrandom
andfrequentspeedyaccessandnotserialaccess.
IndexedAccess:(SYINDEXOperative)
Withstandardtablesandsortedtables,youcanaccessarowbyproviding
therownumber(indexedaccessisthefastestaccess).Thesetables
togetherarecalledasindexedtables.Forthesetables,thesystemfield
SYTABIXcontainstherownumberoperateduponorthenumberofrows
processed,thatis,thesystemfieldSYTABIXisoperativeforthesetables.
Ahashedtablecannotbeaccessedthrougharownumber.Thesystem
fieldSYTABIXisinoperativeforahashedtableandwillcontainavalue
zeroafteranoperationonahashedtable.
Thethreeinternaltabletypesstandard,sorted,andhashedwiththeir
featuresislistedinTable63.
Whentotallyserialorsequentialprocessingisrequired,astandard
tablecanbeused.
Whentheprocessingispartrandomandpartsequential,asorted
tablecanbeused.
Whenprocessingalargeamountofdatawithtotallyfrequent
randomkeyaccess,ahashedtablecanbeused.
Table63.InternalTableTypesFeaturesandAttributes

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

11/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

Whatfollowsaredifferentwaysofdeclaringinternaltablesin4xmode.
Theromannumeralssignifythewaysofdeclaringinternaltablesin4.x
mode.
4.XMode:DeclaringtheInternalTable(andStructureaswell)
byReferringtoaLocal/GlobalStructuredTYPEorLocal/Global
Structure
Globalstructureincludesadatabasetableoranytypeofview.
GeneralSyntax:

DATA<internaltablename>{TYPE|LIKE}{STANDARD|SORTED|HASHED}TABLE
OF<structurename>WITH{UNIQUE|NON_UNIQUE}KEY<field1><field2>...
[INITIALSIZE<n>][WITHHEADERLINE].

INITIALSIZEisequivalenttoOCCURSof3.Xmode.TheINITIALSIZE
clauseisoptional.
TheWITHHEADERLINEhasthesamemeaningasin3.Xmode,thatis,
aninternaltableandastructureofthesamenamegetdefined.
<structurename>iseither

1. AstructuredTYPEdeclaredlocallywiththeTYPESkeyword.The
keywordTYPEnotLIKEshouldbeusedwhenreferringtoit.
Examples:

*Internaltablesdeclaredbyreferringto
*alocalstructureTYPE
TYPES:BEGINOFCUSTOMER_STRU_TYPE,
KUNNRTYPEKNA1KUNNR,
NAME1TYPEKNA1NAME1,
ENDOFCUSTOMER_STRU_TYPE.
DATA:CUSTOMER_ST_TABTYPESTANDARDTABLEOFCUSTOMER_STRU_TYPE.
DATA:CUSTOMER_SR_TABTYPESORTEDTABLEOFCUSTOMER_STRU_TYPE
WITHNONUNIQUEKEYKUNNRINITIALSIZE5.
DATA:CUSTOMER_HS_TABTYPEHASHEDTABLEOFCUSTOMER_STRU_TYPE
WITHUNIQUEKEYKUNNRINITIALSIZE5.

2. AstructuredTYPEdeclaredinDDICobjectTypeGroup.The
keywordTYPEnotLIKEshouldbeusedwhenreferringtoit.
Examples:
*Internaltablesdeclaredbyreferringto
*aDDICstructureTYPEinTypeGroup
TYPEPOOLSYCLG1.
DATA:CUSTOMER_ST_TABTYPESTANDARDTABLEOFYCLG1_CUSTOMER_TYPE
WITHNONUNIQUEKEYKUNNR.
DATA:CUSTOMER_SR_TABTYPESORTEDTABLEOFYCLG1_CUSTOMER_TYPE
WITHUNIQUEKEYKUNNR.
DATA:CUSTOMER_HS_TABTYPESORTEDTABLEOFYCLG1_CUSTOMER_TYPE
WITHUNIQUEKEYKUNNRWITHHEADERLINE.

ATYPEYCLG1_CUSTOMER_TYPEhasbeencreatedintheType
GroupYCLG1asshowninFigure69(repeatofFigure62).

Figure69.TYPEYCLG1_CUSTOMER_TYPEinType
GroupYCLG1[Highlighted]

3. Astructuredeclaredlocally.ThekeywordLIKEnotTYPEshouldbe
usedwhenreferringtoit.
Example:

*Internaltablesdeclaredbyreferringto
*alocalstructure
DATA:BEGINOFCUSTOMER_STRU,
KUNNRTYPEKNA1KUNNR,
NAME1TYPEKNA1NAME1,
ENDOFCUSTOMER_STRU.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

12/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

DATA:CUSTOMER_ST_TABLIKESTANDARDTABLEOFCUSTOMER_STRU
WITHNONUNIQUEKEYKUNNR."definedkeyforstandardtable
DATA:CUSTOMER_SR_TABLIKESORTEDTABLEOFCUSTOMER_STRUWITH
NONUNIQUEKEYKUNNR.
DATA:CUSTOMER_HS_TABLIKEHASHEDTABLEOFCUSTOMER_STRUWITH
UNIQUEKEYKUNNR.

4. AstructuredtypedeclaredinaDDICdatatypeoradatabasetable
oraview.ThekeywordTYPEorLIKEcanbeusedwhenreferring
toit.
Examples:
*Internaltabledeclaredbyreferringto
*aDDICtabledefinition
DATA:CUSTOMER_TABLIKESTANDARDTABLEOFKNA1.
*Internaltablesdeclaredbyreferringto
*aDDICstructure
DATA:CUSTOMER_SR_TABTYPESORTEDTABLEOFYCL_CH06_CUST_STRUWITH
NONUNIQUEKEYKUNNR.
*Internaltabledeclaredbyreferringto
*aDDICview
DATA:CUSTOMER_HS_TABTYPEHASHEDTABLEOFYCL_CH05_VBRKKNAWITH
UNIQUEKEYKUNNR.

ADDICtypestructureYCL_CH06_CUST_STRUisshownin
Figure610(repeatofFigure61).

Figure610.DDICStructureYCL_CH06_CUST_STRU

CreateDDICInternalTableType
Thisisadigressionfromdescribingvariousmodesofinternaltable
declarationsin4.Xmode,whichwillberesumedafterthecoverageof
creationoftheDDICTabletype(internaltabletype).
YoucancreateaDDICinternaltabletype.Youcanthenrefertoitto
declareinternaltablesinABAPprograms.LetaDDICinternaltable
typebecreated.
Beforeyoucreateaninternaltabletype,youneedtohaveaDDIC
structurethatwillbeusedintheDDICinternaltabletype.LetDDIC
objectsthatyouwilluseinyourforthcominghandsonexercisesare
created.
Youaregoingtodoahandsonexerciseofcustomerwisesalessummary.
Eachcustomersbillingdocumentsamountsaresummedoraccumulated
andoutputted.Youwillneedthefollowingfieldstoenableyouto
generatethecustomerwisesalessummary.

EarlieryoucreatedaDDICstructureYCL_CH06_CUST_STRU.Inalike
manner,youwillcreateaDDICstructure
YCL_CH06_SALES_SUM_STRU.Youdonotneedthebillingdocument
currencycodefieldWAERK.ItisincorporatedbecausefortheDDICData
TypeCURRfieldNETWRandthestructuredefinitioninsistsona
correspondingDDICDataTypeCUKYfieldinthestructureorelsewhere.
RecallfromChapter2,DDICDataTypes,theSAPsupplieddatabasetable
viewing.Enterallthesixfieldsinthestructurealongwiththedata
elements.ForthefieldNETWR,(DDICDataTypeCURR),clickonthe
fourthtabCurrency/quantityfields.IntheReferencetablecolumn,enter
thenameofyourstructureYCL_CH06_SALES_SUM_STRUandinthe
Ref.fieldcolumn,enterWAERK.AssigntheEnhancementCategory
(menuoptionExtras)CannotBeEnhanced.Performaconsistencycheck
andactivatethestructure.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

13/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

NowproceedtocreateaDDICinternaltabletype.OntheSE11opening
screen,clickontheradiobuttonDatatype(thirdfromthetop).Enterthe
nameoftheinternaltabletypeobject:YCL_CH06_SALES_SUM_TAB.
ThesystemwillpromptwhetheraDataelement/Structure/Tabletype
istobecreated?ClickontheradiobuttonTabletypeandpresscontinue
(<Enter>).ThescreenoftabLineTypeasshowninFigure611will
appear.

Figure611.CreateTableTypeYCL_CH06_SALES_SUM_TAB:
TabLineType

EntertheShorttext.IntheLineTypetab,threemainradiobutton
optionsappear:
1. LineType:Ifyouwantyourtabletypebestructuredtype,enterthe
nameofthestructurehere(itcanbeaDDICstructure,database
structure,orviewstructure).EntertheDDICstructurecreatedin
thepreviousstep.Youcangetaselectionlistbyenteringthe
patternYCL_CH06*andpressingF4.
2. Ifyouselectthesecondradiobutton,youcanenteroneoftheDDIC
predefinedDataTypes:CHAR,NUMC,andDEC,etc.Youarethen
defininganunstructuredtabletype(whatyoucallthesimple
array).
3. Ifyouselectthethirdradiobutton,youwillenterthenameofthe
referencetype.
Next,clickontheInitializationandAccesstab.Thistabwilllikethatin
Figure612.

Figure612.CreateTableTypeYCL_CH06_SALES_SUM_TAB:
TabInitializationandAccess

Inthistab,youselectthetabletype:standard,sorted,orhashed.There
aretwomoreradiobuttons:(i)IndexedTableand(ii)NotSpecified.
Thesetypesaregeneric.TheyareinthecontextofOOP.Atruntimethe
tabletypecanbedecided.FortheIndexedTable,youcanmakethetable
typeatruntimeeitherastandardorsorted.FortheNotSpecified,you
couldassignatruntimeanyofthetabletypes:standard,sorted,or
hashed.
ThefieldInitialLineNumbercorrespondstotheInitialSizeclausewhen
youdeclareaninternaltableinanABAPprogram.Itisoptional.
Next,clickonthetabkey.AscreenliketheoneshowninFigure613will
appear.

Figure613.CreateTableTypeYCL_CH06_SALES_SUM_TAB:
TabKey

IntheKeydefinitionarea,youcanspecifythetablekey:
1. ClickingtheStandardkeyradiobuttonwillassignallnonnumeric
fieldstothekey.
2. ClickingtheLinetyperadiobuttonwillassignallthefieldsofthe
structuretothekey.
3. ClickingtheKeycomponentsradiobuttonwillenablethescreen
areaKeycomponentsbelowandyoucanselectandassignthe
structurefieldstothekey.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

14/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

4. ClickingtheNotspecifiedradiobuttonwillenablearuntimekey
specification.
IntheKeycategoryarea,youcanoptforUNIQUE,NONUNIQUE,orNot
specified(theNotspecifiedselectionspecifiesakeycategoryatruntime).
Createastandardtablewithastandardkey.Performaconsistencycheck
andactivatethisDDICtabletypedefinition.
InternalTables4.XModeofDeclarationsContinued
4.XMode:DeclaringInternalTablebyReferringtoaDDICTable
Type
OnlykeywordTYPEcanbeused.
Examples:
*Internaltablesdeclaredbyreferringto
*aDDICtabletypenoHEADERLINE
DATA:SALES_SUM_TAB_ST_TAB1TYPEYCL_CH06_SALES_SUM_TAB.
*Internaltablesdeclaredbyreferringto
*aDDICtabletypeWITHHEADERLINE
DATA:SALES_SUM_TAB_ST_TAB2TYPEYCL_CH06_SALES_SUM_TAB
WITHHEADERLINE.

4.XMode:DeclaringNonstructuredInternalTables(Simple
Arrays)
Thenonstructuredinternaltablescanbedeclaredbyreferringtoan
elementarydatatype(local/global)dataobject,(local/global)anddata
elementsimilartothe3.Xmode.
Refertoexamplesof3.X.Youcandeclarestandard,sorted,andhashed
nonstructuredinternaltables.
DeclaringaStructurebyReferringtoanInternalTable
Refertoexamplesof3.X.
Theinternaltableswillbefeaturedinmostofourforthcomingchapters
handsonexercises.Youwillsticktodeclaringtablesin4.Xmodeonly.
YouwillalsotrytoavoidtheWITHHEADERLINEfeature(where
internaltableandstructurenamesarethesame).Thismodeof
declarationisnotsupportedintheOOPenvironment.
Tostartwith,youwilldoacoupleofsimplehandsonexerciseswith
internaltabledeclarationsin4.Xmode.
HandsOnExercise:SplitaString,GetOutputinNonstructured
InternalTable
InChapter4,youhadusedaSPLITstatementtosplitastringintoits
constituentwordsandeachwordreturnedinaseparatevariable.The
issuewasposedthatthenumberofwordsinastringintherealworld
cannotbepredetermined.TheSPLITstatementusedinChapter4was
notapracticalfeature.Withinternaltables,avariationoftheSPLIT
statementwillgeteachwordofastringinaseparaterow.Sotheissueof
apredeterminednumberofwordsinastringisresolved.
Thesourceprogram:

REPORTYCL_CH06_ITAB03NOSTANDARDPAGEHEADING.
****************************************************************
*InternalTablesSplitaString&GetWordsIntoitabRows**
****************************************************************
*****************************************
*PARAMETERSinputstring**
***
*performSPLITstatement,eachword**
*willbereturnedasarowinthe**
*unstructuredinternaltable**
***
*setLOOPAT...ENDLOOPtooutput**
*rowsofunstructuredinternaltable**
*****************************************
DATA:WORD(15)TYPEC,
WORDS_TABLIKESTANDARDTABLEOFWORD."unstructuredinternaltable
PARAMETERS:ISTRING(50)TYPECDEFAULT
'ONCEUPONATIMETHERELIVEDANERD'.
*****************************************************************
STARTOFSELECTION.
SPLITISTRINGAT''INTOTABLEWORDS_TAB."eachwordreturnedasarow
LOOPATWORDS_TABINTOWORD.
WRITE:/5WORD.
ENDLOOP.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

15/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

TheoutputwillappearlikethatinFigure614.

Figure614.ProgramYCL_CH06_ITAB03:Output

SORTStatement
Thisisastatementtoorderrowsofinternaltables.Youhavealready
usedasimpleversionofthisstatementinthehandsonexercise:
CustomerWiseListofBillingDocumentsofaSpecifiedCompanyCode.
Thestatementcanbeusedforstandardandhashedtables.Thesyntax
anddifferentformsofthisstatement:
SORT<internaltablename>[ASCENDING|DESCENDING][ASTEXT]
[STABLE].
Thisformofthestatementsortsthetableinascending(lowestvaluesfirst
andhighestvalueslast)/descending(highestvaluesfirstandlowest
valueslast)orderofdefinedkeyfieldsofthetable.Forthestandard
tables,ifkeyfieldsareundefined,thesortingwillbeperformedinthe
orderofthestandardkeyfields.IftheorderASCENDING|DESCENDING
isomitted,bydefaultitwillsortinascendingorder.Thesortfieldsinthis
formofsortstatementareimplicit.TheASCENDING|DESCENDING
appliestoallkeyfields.Youdonothavetheoptiontospecify
ASCENDING|DESCENDINGforeachfieldseparately.
Theoption[ASTEXT]isapplicabletoTYPECfields.Itisspecifiedfor
alphabeticsorting.ThecodesusedtostorecharactersinbytesASCII,
EBCDIC,etc.,wereorganizedtostoreEnglishalphabetletters.Other
EuropeanlanguagessuchasGermanandFrenchcontainextravowels
(morethanfive).Theseextravowelsarenotcontainedinthealphabetic
rangeoftheASCIIorEBCDICcodes.Ordinarysortingwillgobythebyte
value.Forexample,theGermanalphabethasthevowel.(owithtwo
dotsontop),andthevowelintheGermanalphabetsetoccursafterthe
lettero.ButintheASCIIorEBCDICcode,itoccursafterz.Totakecareof
this,SAPhasprovidedthefeatureTEXTsorttogeneratetruealphabetic
order.Ahandsonexercisedemonstratesandelucidatesthisissuebetter.
AhandsonexerciseonTEXTsortfollowsthesortsyntaxexplanations.
TheoptionSTABLEisrelevantinthecontextofaninternaltablebeing
sortedagainandagainonthesamekeyfields.Theoptionensuresthat
orderofmultiplekeyvaluesisretainedaftereverysortonthesamekey
fields.
Thesecondformofsortstatementis:
SORT<internaltablename>[STABLE]BY<field1>[ASCENDING|DESCENDING]
[ASTEXT]<field2>[ASCENDING|DESCENDING][ASTEXT].......

Thefieldsonwhichsortingaretobeperformedareexplicit.Foreach
field,youhavetheoptionofASCENDING|DESCENDING.
APPENDStatement
TheAPPENDstatementcanbeusedonlyforindexedtables,thatis,
standardandsorted.Forsortedtables,itisnotadvisabletousethe
APPENDstatement.Withthisstatement,youcan(i)transferthecontents
ofthestructureasanewrowintheinternaltable,(ii)createanewblank
rowintheinternaltable,or(iii)transferrowsfromasourceinternal
tabletoadestinationinternaltable.Inthesethreeoperations,thenew
rowsareaddedattheendoftheexistingrowsinthedestinationinternal
table.
Mostofthetime,youareusing(i),sotheAPPENDstatementis
elaboratedonhereinthiscontext.Iftheinternaltableisemptytostart
with,anAPPENDstatementwilltransferthestructurecontentsasthe
firstrowintheinternaltable.AsecondAPPENDwilltransferthe
structurecontentsasasecondrowintheinternaltableandsoon.Itcan
beusedinascenariosuchaswhereaninternaltablehastobefilledrow
byrow.Thisisunlikethewayyouhavefilledinternaltablesuntilnow:
multiplerowsdumpedfromadatabasetableorviewintoaninternal
table.AgraphicrepresentationofthisformofAPPENDstatementis
showninFigure615.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

16/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

Figure615.OperationofAPPENDStatement

HandsOnExercise:InternalTableTextSort(UseAPPENDto
PopulateInternalTable)
YouwillusetheAPPENDstatementtofillanunstructuredinternaltable
withdatahavingtheadditionalvowelstoaddtoEnglish.Youwillassign
literalvaluescontainingextravowelstotheelementaryfieldand
APPENDthevalueofelementaryfieldtotheinternaltable.Thisisoneof
thefewtimesyouareusingliteralsinanABAPprogram.Youwill
performthesortwithouttheASTEXToptionandoutputfromtheinternal
tablenextperformthesortwiththeASTEXToptionandoutputfromthe
internaltableandnotetheresults.
Thesourceprogramis:

REPORTYCL_CH06_ITAB04.
***************************************
*InternalTables:APPEND,TEXTSORT**
***************************************
************************************************************
*declaresimple/nonstructuredTYPECinternaltable**
*in4.Xmode**
***
*fillthistablewithtextcontainingextravowels**
*throughAPPENDstatement**
***
*outputtablerowsLOOP...ENDLOOP**
*outputwillappearinorderinwhichrowswereappended**
***
*performordinarysortonthetable**
*outputwillappearinorderofbytevalues**
***
*performtextsortonthetable**
*outputwillappearintruealphabeticorder**
************************************************************
TYPES:NAME_TYPE(25)TYPEC.
DATA:NAMESTYPESTANDARDTABLEOFNAME_TYPEWITHHEADERLINE
INITIALSIZE0."unstructuredinternaltable
NAMES='BLLINGER'.
APPENDNAMESTONAMES."addsarowattheend
NAMES='BOLLINGER'.
APPENDNAMESTONAMES.
NAMES='BILLINGER'.
APPENDNAMESTONAMES.
NAMES='BLLINGER'.
APPENDNAMESTONAMES.
NAMES='BULLINGER'.
APPENDNAMESTONAMES.
FORMATINVERSEONCOLORCOL_TOTAL.
WRITE:/5'OriginalData:'.
LOOPATNAMES.
WRITE:/5NAMES.
ENDLOOP.
SORTNAMES.
SKIP.
FORMATINVERSEONCOLORCOL_KEY.
WRITE:/5'OrdinarySort:'.
LOOPATNAMES.
WRITE:/5NAMES.
ENDLOOP.
SORTNAMESASTEXT.
SKIP.
FORMATINVERSEONCOLORCOL_POSITIVE.
WRITE:/5'TextSort:'.
LOOPATNAMES.
WRITE:/5NAMES.
ENDLOOP.

Theoutputwillappearlikethis:

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

17/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

Figure616.ProgramYCL_CH06_ITAB04:Output

TheordinarysortisplacingBLLINGERandBLLINGERattheend.
ThetextsortispositioningBLLINGERafterBILLINGERand
BLLINGERafterBOLLINGER.
HandsOnExercise:CustomerWiseSalesSummaryofa
SpecifiedCompanyCodeUsingtheCOLLECTInternalTable
StatementonaStandardTable
Youwillproduceacustomerwisesalessummary.Lettheoutputbe
orderedcustomerwise.Inthisoutput,ifacustomerhasnnumberof
billingdocuments,theamountsofthisnnumberofbillingdocumentsare
accumulated,andthetotalamountofthecustomeralongwiththe
customercode,name,andcitywillappearasonelineintheoutput.Since
youareaddingamountfigures,theyneedtobeconvertedtoasingle
currency:theoperatingcurrencyofthecompanycode.Youwillusethe
exchangeratefieldtoconverttheamountfromdocumentcurrencytothe
operatingcurrency.
Summaryoutputlistsareaverycommondemandinenterprises.
Output
Theroughlayoutofthecustomerwisesalessummarywillappearlike
this:

Theoutputbodylayout:
Table64.OutputBodyLayout

Inputs
Theinputdataforthisoutputwillbeourdatabaseview
YCL_CH05_VBRKKNA.
TodeclaretheinternaltableintheABAPprogram,youwillrefertothe
DDICtabletypeYCL_CH06_SALES_SUM_TAByoucreatedearlierin
thischapter.
COLLECTStatement
YouwillbeusingtheCOLLECTstatementtoproducethesummary.The
COLLECTstatementisahandyfeaturetoconsolidateorsummarizedata.
WiththeCOLLECTstatementyoucangenerateaonelevelsummary.
Youaresummarizingdataherebasedonthecustomer.Ifyouwere
requiringalistforeachcustomerofhowmuchofmaterialAwassoldand
howmuchofmaterialBwassoldthatis,atwolevelsummaryoutput
involvingthecustomerandmaterial,theCOLLECTstatementcannotbe
used.
AnunderstandingoftheCOLLECTstatementiscrucial.TheCOLLECT
statementworksforalltabletypes:standard,sorted,orhashed.Inthe
currenthandsonexercise,youareusingastandardtable.Sofornow,

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

18/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

thediscussionoftheCOLLECTstatementisinthestandardtablecontext.
Subsequently,therewillbediscussionsoftheCOLLECTstatementinthe
contextofsortedandhashedtables.
ThesyntaxoftheCOLLECTstatement:
COLLECT<structurename>INTO<internaltablename>.

COLLECTStatementOperation
LikeinanAPPENDstatement,thereisatransferofdatafromastructure
toaninternaltable,butinapeculiarway.
TheCOLLECTstatementisatwoinonestatement.Itoperatesonthe
basisofthestandardkeyvalues.Sothestandardtableonwhichyou
operateaCOLLECTstatementmustnothaveadefinedkeyoradefined
keythatisthesameasthestandardkey.Recallthatthestandardkeyof
aninternaltableconsistsofallthestructurefieldsoftypeC,D,N,andT.
TheCOLLECTstatementfirstcheckswhetherthestandardkeyvaluein
thestructurehasanycorrespondingrowinthetable.
Ifnorowexistswiththestandardkeyvaluesofthestructureinthe
table,thestructuredatawillgoasanewrowinthetablethisis
effectivelyanAPPENDoperation.
Ifarowexistsinthetableofthestandardkeyvaluesinthe
structure,thenumericfieldvaluesfromthestructureareaddedto
thenumericfieldvaluesinthecorrespondingrowinthetable.
NumericfieldsinthepresentcontextwillmeantypeF,I,andP.
ThetypeNfieldsaspartofstandardkeyarenotconsidered
numericfields.
Anexamplewillhelpelucidatethis.Lettherebeaninternaltablewith
thefollowingstructure:

DATA:BEGINOFEMP_STRU,
DEPT_CODE(2)TYPEC,
EMP_CODE(4)TYPEN,
POINTS(3)TYPEPDECIMALS0,
ENDOFEMP_STRU,EMP_TABLIKESTANDARDTABLEOFEMP_STRU.

ThestandardkeyinthisinstancewillbeDEPT_CODE,EMP_CODE.Let
valuesbeassignedtothestructurefieldsandtheCOLLECTstatementbe
operatedontheinternaltable.

EMP_STRUDEPT_CODE='A1'.
EMP_STRUEMP_CODE=1234.
EMP_STRUPOINTS=100.
COLLECTEMP_STRUINTOEMP_TAB."thiswilloperateasanAPPEND
"firstrowA11234100
EMP_STRUPOINTS=200.
COLLECTEMP_STRUINTOEMP_TAB."rowwithstandardkeyvaluesA11234
"alreadyexists,200willbeadded
"to100.firstrow:A11234300
EMP_STRUDEPT_CODE='A1'.
EMP_STRUEMP_CODE=1236.
EMP_STRUPOINTS=400.
COLLECTEMP_STRUINTOEMP_TAB."thiswilloperateasanAPPEND
"secondrow:A11236400
EMP_STRUDEPT_CODE='B1'.
EMP+_STRUEMP_CODE=1234.
EMP_STRUPOINTS=100.
COLLECTEMP_STRUINTOEMP_TAB."thiswilloperateasanAPPEND
"thirdrow:B11234100
EMP_STRUDEPT_CODE='A1'.
EMP_STRUEMP_CODE=1236.
EMP_STRUPOINTS=100.
COLLECTEMP_STRUINTOEMP_TAB."rowwithstandardkeyvalesA11236
"alreadyexists,100willbeaddedto400
"secondrow:A11236500
Attheendoftheaboveoperations,theinternaltablewillcontain:
A11234300
A11236500
B11234100

IfyouwanttooutputthesummarytableattheendofCOLLECT
statementsoperation,youneedtohaveaLOOP
AT...WRITE...ENDLOOP.
AninternaltablewithonlytheCOLLECTstatementoperatingonitina
loopconstruct(SELECT...ENDSELECT)willresultattheendwithunique
standardkeyvalues,andthenumericfieldsofstandardkeyvalueswill
besummarized.
Howyouframethetablestructurestandardkeyconsistingofthenon
numericfieldsiscritical.Thesummarizationoccursonitsbasis.
Revertingtoyourhandsonexercise,yourtablestructureshouldbe:

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

19/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

KUNNRCustomerCode
NAME1Name
ORT01City
NETWRBillingDocumentNetValue
KURRFExchangeRate

YourstandardkeywillconsistofKUNNR,NAME1,andORT01(non
numericfields).Youonlyneedtosummarizeonthebasisofcustomer
codeKUNNR,butyouneedNAMEandORT021inyouroutput.The
additionofthesetwofieldsinthestandardkeydoesnotaffecttheresults
inanyway.
ThetwonumericfieldsNETWRandKURRFwillbeaccumulated.Youdo
notneedtohaveKURRFaccumulated.Itmakesnosensetototal
exchangerate.YouneedtheKURRFofeachrowfromtheview(each
uniquevalueofthebillingdocument)toconvertthenetbillingdocument
valueNETWRfrombillingdocumentcurrencytotheoperatingcurrency
ofthecompanycode.Butyoucanthelpit.TheCOLLECTstatement
accumulatesallnumericfields.Youhavetoignoretheaccumulationof
KURRF.TheaccumulationofKURRFmightresultinanumericover
flow.Thisoverflowissuecanbeaddressedasyouwillsee.
Youwillinputthecompanycodeforwhichasalessummaryisrequired
(PARAMETERS...).Tobuildyourcustomerwisesalessummaryinternal
table,youhavetohaveaSELECT...ENDSELECTloopingconstructwith
yourdatabaseviewYCL_CH05_VBRKKNA.Aftereachrowisfetched
fromthedatabaseview,youmustissuetheCOLLECTstatementinthe
SELECT...ENDSELECTloop.AttheendoftheSELECT...ENDSELECT
loop,yoursummarizedtablewillbeready.Youwillsortthetableon
KUNNR,youwillthenuseLOOP...WRITE...ENDLOOP...tooutputyour
sortedsummarytable.AttheendofLOOP...ENDLOOP...youwilloutput
thegrandtotal.
Thesourceprogramtogenerateacustomerwisesalessummaryofa
specifiedcompanycodeusingCOLLECTstatementonastandardtable
is:

REPORTYCL_CH06_ITAB05LINESIZE120LINECOUNT60
NOSTANDARDPAGEHEADING.
********************************************************
*CustomerWiseSalesSummaryofacompanycodeusing**
*COLLECTstatement**
********************************************************
**********************************************************
*declareinternaltablebyreferencetoDDICtable**
*type.declarestructurebyreferencetointernal**
*table**
***
*PARAMETERStoinputcompanycode**
*SELECTSINGLE..tofetchcompanycodename(BUTXT)**
*operatingcurrencyofcompanycodeWAERS**
***
*SELECT...ENDSELECTtofetchrowsfromdatabaseview**
*multiplyNETWRKURRFtoconvertNETWRtooperating**
*currency.initializeKURRFto0aftermultiplication**
*topreventKURRFaccumulationoverflow.**
*issueCOLLECT**
***
*atendofSELECT...ENDSELECT,summarytablecreated**
***
*sortsummaryinternaltablebyKUNNR**
***
*setupLOOP...WRITE...ENDLOOP**
***
*endofLOOP..WRITE...ENDLOOPoutputgrandtotal**
**********************************************************
DATA:SALES_TABTYPEYCL_CH06_SALES_SUM_TAB,"keywordTYPEonly
SALES_STRULIKELINEOFSALES_TAB,"declarestructureby
"referringtointernal
"table
TOTALTYPEVBRKNETWR,
BUTXTTYPET001BUTXT,
WAERSTYPET001WAERS,
BUTXTSTYPESTRING.
**********************************************
PARAMETERS:CCODETYPEVBRKBUKRSDEFAULT3000.
**********************************************
TOPOFPAGE.
WRITE:/5TEXT001,CCODENOGAP,'/'NOGAP,BUTXTS,102TEXT003,
107(3)SYPAGNO.
WRITE:/40TEXT002,WAERS.
SKIP1.
WRITE:/5(104)SYULINE.
WRITE:/5TEXT004,11TEXT005,23TEXT006,60TEXT007,91(17)
TEXT008RIGHTJUSTIFIED.
WRITE:/5TEXT009,13TEXT010.
WRITE:/5(104)SYULINE.
**********************************************
STARTOFSELECTION.
SELECTSINGLEBUTXTWAERSFROMT001INTO(BUTXT,WAERS)WHERE
BUKRS=CCODE.
BUTXTS=BUTXT."assignmenttoTYPESTRINGdropstrailingblanks

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

20/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

SELECTKUNNRNAME1ORT01NETWRKURRFFROMYCL_CH05_VBRKKNAINTO
CORRESPONDINGFIELDSOFSALES_STRUWHEREBUKRS=CCODE.
SALES_STRUNETWR=SALES_STRUNETWR*SALES_STRUKURRF.
SALES_STRUKURRF=0."topreventoverflow
COLLECTSALES_STRUINTOSALES_TAB.
ENDSELECT.
SORTSALES_TABBYKUNNR.
LOOPATSALES_TABINTOSALES_STRU.
WRITE:/5(4)SYTABIX,SALES_STRUKUNNRUSINGNOEDITMASK,
SALES_STRUNAME1,SALES_STRUORT01,(17)SALES_STRUNETWR.
TOTAL=TOTAL+SALES_STRUNETWR.
ENDLOOP.
SKIP1.
WRITE:/(17)TOTALUNDERSALES_STRUNETWR.

TheSELECTstatementintheprogramis:
SELECTKUNNRNAME1ORT01NETWRKURRFFROMYCL_CH05_VBRKKNA
INTOCORRESPONDINGFIELDSOFSALES_STRUWHEREBUKRS=CCODE.

YouareusingavariationoftheSELECTstatementwith
CORRESPONDINGFIELDSOF.Thisvariationistobeusedwhenever
thesourceanddestinationarenotidentical.Inyourpresentsituation,
thedatabaseview(source)doesnothavethefieldcurrencycodeWAERK
presentinyourdestinationstructure.Thisisanalogoustothestatement
MOVECORRESPONDINGtobeusedwhenmovingdatafromasource
structuretoadestinationstructurethesourceanddestinationarenot
identicalintermsofnumberoffieldsand/ororderingofthefieldsinthe
structures(Chapter4).
ThecurrencycodeDDICDataTypeCUKYfieldWERKhadtobe
incorporatedinyourDDICstructureYCL_CH06_SALES_STRUtotake
careoftheDDICDataTypeCURRfield(NETWR)havinga
correspondingCUKYfield.
Thetextsymbolsfortheprogramare:

Figure617.ProgramYCL_CH06_ITAB05:TextSymbols

Theprogramoutputwillbelikethis:

Figure618.ProgramYCL_CH06_ITAB05:Output

Figure619.ProgramYCL_CH06_ITAB05:TotalOutput

Youhavegeneratedthecustomerwisesalessummaryforaspecified
companycodeasperyourspecifications.YouemployedtheCOLLECT
statementonastandardtable.TheCOLLECTstatementoperatesonthe
basisofthestandardkey.TheCOLLECTstatementisatwoinone
statement,APPENDandupdatingofnumericfields.YouusedaDDIC
definedtabletypetodeclaretheinternaltable.
HandsOnExercise:CustomerWiseSalesofaSpecified
CompanyCodeUsingCOLLECTInternalTableStatementona
SortedTable
Letthisexerciseberepeatedwithasortedtable.Youwilldefinethe
sortedinternaltableintheABAPprogramitselfunliketheprevious

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

21/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

exercisewhereyouhaddefinedthestandardtableintheDDIC.Forthis
sortedtable,youhavetodefinethekey.Thedefinedkeymusthaveall
thefieldsofthestandardkey,thatis,fieldsofTYPEC,D,N,andTforthe
COLLECTstatementtooperate.
Ifthedefinedkeyhasallthestandardkeyfields,onlythentheCOLLECT
statementwillbeacceptedatthesourcelevel.Ifyourdefinedkeyis
differentfromthestandardkeyfields,asyntaxerroroccursduring
compilation.
Inasortedinternaltable,rowsarealwaysintheascendingorderofkey
values.TheoperationoftheCOLLECTstatementwouldensurethis.So
youcansaythattheCOLLECTstatementforasortedtableisatwoin
onecommand:ifthekeyvaluesinthestructuredonotexistinthetable,a
rowINSERTwilloccur(insteadofAPPENDinthecaseofstandardtable),
andtherowwillbeinsertedattheappropriateposition.Ifthestructure
keyvalueexists,thenumericfieldvaluesfromthestructureareaddedto
thenumericfieldsofthecorrespondingrowinthetable.
YoucancopytheprecedingexercisesABAPprogramandmake
appropriatechangesorcodeanewprogram.YoucanmakeacopyABAP
programwithadifferentnamefromtheSE38openingscreen.Enterthe
nameofthesourceprogramtobecopied,andclickonthebutton
ontheapplicationtoolbar.Thesystemwillpromptforthenameofthe
destinationprogram(YCL_CH06_ITAB06).Thecopiedprogramwillbe
inaninactivestate.YoucanrenameprogramsfromtheSE38opening
screenbyenteringthenameoftheABAPprogramandclickingonthe

button

ontheapplicationtoolbar.

Copyandactivatethetextsymbolsfromtheprecedingexerciseintothe
currentoneusingtransactioncodeSE32.
Intheprecedingexercise,yousortedthesummarytablegenerated.In
thecurrentexercisethisisunnecessaryasourtableisasortedtable.The
restofthestatementsarethesameasintheprecedingexercise.
Thesourceprogramisavailableinthesourceprogramsresource.
ExecuteandtallytheresultswiththeresultsofYCL_CH06_ITAB05.The
resultsshouldbeidentical.
Untilnow,youhavefilledaninternaltablewithaSELECTstatement
usinganAPPENDstatementandaCOLLECTstatement.Youhave
retrievedrowsfromaninternaltableonlywiththeLOOP...ENDLOOP
construct:fetchingonerowatatimesequentiallyfromtheinternaltable
intostructure.
TheAPPENDstatement,eventhoughitcanbeused,hypothetically,for
indexedtables,thatis,standardandsortedtables,shouldbeusedon
standardtables.Insortedtables,whenyouuseanAPPENDstatement,
thestructurekeyfieldvalueshouldbegreaterthanorgreaterthanor
equalto(dependingonthedefinedkeytobeUNIQUE/NONUNIQUE)
thehighestkeyvalueinthetable.RecallthattheAPPENDstatement
addstherowattheveryend.SoifyoutrytoAPPENDtoasortedtable,
therowshouldbeabletofitattheend.Ifthisdoesnthappen,aruntime
erroroccurs.Youcantestthisoutasanexercise.
HandsOnExercise:READwithIndex(RetrieveaRowGivena
RowNumber)
Theindexedtables(standardorsorted)allowyoutoretrievedataofany
rowfromthetableintoastructure(READwiththeindexstatement).You
havetoprovidetherownumber.Iftherownumberexists,therowwillbe
fetchedfromthetableintothestructureiftherownumberdoesnotexist,
thisisanerrorcondition.IntheABAPprogrammingenvironment,you
useasystemfieldtoascertaintheresultofanoperation.Thesystemfield
isSYSUBRC.Ifafteranoperationthesystemfieldcontainsazerovalue,
theoperationissuccessfulotherwiseitisafailure.ThesyntaxofREAD
withIndexis:
READTABLE<internaltablename>
INDEX<Variable/literal>/<constant>
INTO<structurename>
[TRANSPORTING{<field1>[<field2>..]}|{ALLFIELDS}|{NOFIELDS}.

<Variable/literal>Youcansupplyeitheravariable(thevariable
mustcontainanumber)oranumericliteral.
IftheadditionTRANSPORTING<field1><field2>...isused,you
havetheoptiontotransferselectedfieldsfromatableintothe
structure.
IftheadditionTRANSPORTINGNOFIELDSisused,theINTO
<structurename>shouldbeomitted.Inthiscase,whentheread
operationisperformedandthesuppliedrownumberexists,itwill
setthesystemfieldSYTABIXtotherownumbervalueandsetthe
systemfieldSYSUBRCtozero.Ifthesuppliedrowdoesnotexist,

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

22/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

thesystemfieldSYTABIXissettozeroandthesystemfieldSY
SUBRCissettoanonzerovalue.
IftheadditionTRANSPORTINGALLFIELDSisused,allthefields
willbefetchedfromthetableintothestructure.Bydefaultallthe
fieldsarefetchedfromthetabletothestructure.
Iftherownumberprovidedexists,thesystemfieldSYTABIXisset
tothevalueoftherownumber,andthesystemfieldSYSUBRCis
settozero.
Inyourexerciseprogram,youhavedeclaredastructureTABLES
TCURT.ThedatabasetableTCURTisatexttable.Itiscontaining
theworldscurrencydescriptionsinallthelanguagessupportedby
SAP.TheTCURTstructure:

Referringtothisstructure,youhavedeclaredaninternaltableof
typesorted.Youareloadingthisinternaltablefromthedatabase
tableTCURTwithonlythecurrencydescriptionsoftheloggedin
language:WHERESPRAS=SYLANGU.
YouareretrievingarowthroughthePARAMETERSvariable
ROW_NO.YouhavegiventheadditionTRANSPORTINGWAERS
LTEXT.ThiswillfetchdataofonlytwofieldsWAERSandLTEXT.
YouarecheckingifSYSUBRC=0(retrievalsuccessful)thenyou
outputthecurrencycode(WAERS),thelongtext(LTEXT),andthe
shorttext.(KTEXT)KTEXTwillbeoutputasblank/spaceasyouare
notretrievingthisfieldfromtableintothestructure.IfSYSUBRC
isnonzero,youarehighlightingROW_NOasaninvalidrow
number.
TheSourceprogram:
REPORTYCL_CH06_ITAB07.
***********************************
*InternalTableREADWithIndex**
***********************************
******************************************
*declareTABLESTCURT.declaresorted**
*tablewithTCURTstructurekeyWAERS**
***
*inputrecord/rowno.(PARAMETERS)**
***
*loadinternaltablefromTCURTWHERE**
*SPRAS=SYLANGU**
***
*issueREAD..INDEX..**
*checkSYSUBRC&output**
******************************************
TABLESTCURT."localstructurehavingallfields
"ofdatabasetableTCURT
DATA:CURR_TABTYPESORTEDTABLEOFTCURTWITH
UNIQUEKEYWAERS.
************************************************
PARAMETERS:REC_NO(4)TYPENDEFAULT75.
STARTOFSELECTION.
SELECT*FROMTCURTINTOTABLECURR_TABWHERE"*(star)justified.table
SPRAS=SYLANGU."consistsoffewfields
READTABLECURR_TABINTOTCURTINDEXREC_NO"fetchonly
."TRANSPORTINGWAERSLTEXT."WAERSLTEXT
IFSYSUBRC=0.
FORMATINVERSECOLORCOL_POSITIVE.
WRITE:/5(4)SYTABIX,TCURTWAERS,TCURTLTEXT,TCURTKTEXT.
ELSE.
FORMATINVERSECOLORCOL_NEGATIVE.
WRITE:/5'RowNo.:',REC_NO,'Invalid'.
ENDIF.

CommenttheTRANSPORTINGadditionintheREAD...statementand
confirmthatthevalueoffieldKTEXTisoutput.
ExecutetheprogramwithahighvalueofREC_NOtotriggeraninvalid
rowcondition.
Theoutputswilllooklikethis:

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

23/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

Figure620.ProgramYCL_CH06_ITAB07:WithREC_NO=75
&TRANSPORTINGWAERSLTEXT

Figure621.ProgramYCL_CH06_ITAB07:WithREC_NO=555

Figure622.ProgramYCL_CH06_ITAB07:WithREC_NO=75
&TRANSPORTINGOptionCommented

HandsOnExercise:READ...WITHKEY...(RetrieveaRowGiven
KeyFieldValues)
Fetcharowfromthetableintothestructurecorrespondingtothe
suppliedtablekeyfieldvalues.
ThesyntaxofREAD...WITHKEY...statementis:

READTABLE<internaltablename>
WITHKEY<keyfield1>=<dataobject1>
[<keyfield2>=<dataobject2>..]
[BINARYSEARCH}
INTO<structurename>[TRANSPORTINGoptions].

The<dataobject1>canbevariables,literals,andhypothetically
constants.
TheTRANSPORTINGoptionsareTRANSPORTINGALLFIELDS|
TRANSPORTINGNOFIELDS|TRANSPORTING<field1>[<field2]...
Thisstatementworksforallthethreetabletypes:standard,sorted,and
hashed.
Forthesortedtable,abinarysearchmethodisusedtolocatearowofthe
suppliedkeyfieldvalues.Thisisthewaydatafromasortedtableistobe
retrievedonarandombasis.
Forthehashedtable,thehashedalgorithmisusedtolocatearowofthe
suppliedfieldvalues.ThisREADstatementshouldbeusedtoretrieve
datafromahashedtablewhenfrequentlyaccessingonrandombasis(key
fieldvalueschanging)fromaverylargenumberofentries.
Forthestandardtable,abinarysearchmethodisusedtolocatearowof
thesuppliedfieldvaluesifthekeyphraseBINARYSEARCHisspecified
withthestatement.Itshouldbeensuredthatthetableisintheascending
orderofthekeyfieldvalues.Ifthisadditionalphraseisnotspecifiedwith
thestatement,thesystemwillusethelinearsearchmethodtolocatea
rowwiththesuppliedkeyfieldvalues.
Youwillrepeattheexerciseyoudidwith3.Xdeclarationofinternal
tables:listingoutthebillingdocumentsofaspecifiedcompanycode.In
thishandsonexercise,youwereloadinganinternaltablewithdatafrom
thedatabaseview(createdwithtablesVBRKandKNA1).Subsequently
yououtputfromtheinternaltablewiththeLOOP...WRITE...ENDLOOP
statements.
Inthepresenthandsonexercise,youwillnotusetheview.Youwillload
oneinternaltable(standardsequential/serialprocessing)say,itabI
withdatafromthedatabasetableVBRKofaspecifiedcompanycode
(WHEREBUKRS=...)Youwillchoosethefollowingfieldsfromthis
databasetable:
VBELNBillingDocumentNumber
FKDATBillingDocumentDate
KUNAGCustomerCode
NETWRNetValueinDocumentCurrency
KURRFExchangeRate

Youwillloadasecondinternaltable(hashedfrequentrandomaccess)
say,itabIIwithdatafromthedatabasetableKNA1.Youwillchoosethe

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

24/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

followingfieldsfromthisdatabasetable:

KUNNRCustomerCode
NAME1Name
ORT01City

Youneedtooutputthefollowingfields:
SRL_NO(internaldataobject/programvariable)
VBELN
FKDAT
NAME1
ORT01
NETWRthiswillbeNETWR*KURRF

Youwillhavetheoutputinorderofbillingdocumentnumber(i.e.,
VBELN).
YouwillsetaLOOP...ENDLOOPwithitabI.Youcanoutputfields
VBELN,FKDAT,KUNAG,andNETWRfromthisinternaltable.Forthe
fieldsNAME1,ORT01,youwillreadtheitabIIthroughREAD...WITH
KEY...RetrievingcustomerinfoNAME1,ORT01withKUNAGofitabI.
Youcancopytheearlierprogramintoanewnameorcodetheprogram
fromscratch.Ifyoucodetheprogramfromscratch,youcancopytext
symbolsfromtheearlierprogramusingthetransactioncodeSE32and
activate.
Thiswholeexerciseistodemonstratethefrequentrandomaccessofan
internaltable(hashed)usingREAD...WITHKEY...Statement.
ThesourceprogramtogenerateaListofBillingDocumentsofaspecified
companycodeusingtwointernaltables:astandardtableandahashed
tableis:

REPORTYCL_CH06_ITAB08LINESIZE135LINECOUNT60
NOSTANDARDPAGEHEADING.
****************************************************************
*ListofBillingDocsofaSpecifiedCompanyCodewithTotal**
*UsingTwoInternalTables**
****************************************************************
*******************************************************************
*declare2structures&internaltables:(1)loadingdatafromVBRK**
*(2)loadingdatafromKNA1**
***
*PARAMETERSCCODETYPEVBRKBUKRSVALUECHECKDEFAULT3000**
*toselectcompanycode**
***
*getBUTXTWAERSfromT001SELECTSINGLEetc.**
***
*loadinternaltable<iatb1>fromtheVBRK**
*SELECT<fields>fromVBRKINTOTABLE<itab1>**
*WHEREBUKRS=CCODE.**
***
*loadinternaltable<iatb2>fromtheKNA1**
*SELECT<fields>fromKNA1INTOTABLE<itab2>.**
***
*setLOOPAT<itab>into<itab>.**
*calculateamountinoperatingcurrencyofchosenCCODE**
***
*RetrieveNAME1,ORT01from<itab2>byREAD..WITHKEY..**
*fromsecondinternaltable<itan2>**
*incrementSRL_NO(serialno)**
*WRITE...**
*buildtotal**
*ENDLOOP.**
***
*outputtotal**
***
*******************************************************************
TABLES:T001.
DATA:BEGINOFBILL_DOCS_STRU,
VBELNTYPEVBRKVBELN,
FKDATTYPEVBRKFKDAT,
KUNAGTYPEVBRKKUNAG,
NETWRTYPEVBRKNETWR,
KURRFTYPEVBRKKURRF,
ENDOFBILL_DOCS_STRU,
BILL_DOCS_TABLIKESTANDARDTABLEOFBILL_DOCS_STRU,
BEGINOFCUST_INFO_STRU,
KUNNRTYPEKNA1KUNNR,
NAME1TYPEKNA1NAME1,
ORT01TYPEKNA1ORT01,
ENDOFCUST_INFO_STRU,
CUST_INFO_TABLIKEHASHEDTABLEOFCUST_INFO_STRU
WITHUNIQUEKEYKUNNR,
STRNGTYPESTRING,
SRL_NOTYPESYTABIX,
TOTALTYPEVBRKNETWR.
PARAMETERSCCODETYPEVBRKBUKRSDEFAULT3000VALUECHECK.
*********************************************************************
TOPOFPAGE.
WRITE:/5STRNG,129(3)SYPAGNO.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

25/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

SKIP1.
WRITE:/5(127)SYULINE.
WRITE:/5TEXT003,11TEXT004,22TEXT005,33TEXT006,46TEXT007,
83TEXT008,126TEXT009.
WRITE:/6TEXT010,35TEXT011.
WRITE:/5(127)SYULINE.
***********************************************************************
STARTOFSELECTION.
SELECTSINGLE*FROMT001WHEREBUKRS=CCODE.
CONCATENATETEXT001CCODE'/'T001BUTXTTEXT002T001WAERSINTOSTRNG.
SELECTVBELNFKDATKUNAGNETWRKURRFFROM
VBRKINTO
TABLEBILL_DOCS_TAB
WHEREBUKRS=CCODE.
SELECTKUNNRNAME1ORT01FROM
KNA1INTO
TABLECUST_INFO_TAB.
********************************************************************
SORTBILL_DOCS_TABBYVBELN."defaultisASCENDING
LOOPATBILL_DOCS_TABINTOBILL_DOCS_STRU.
BILL_DOCS_STRUNETWR=BILL_DOCS_STRUNETWR*BILL_DOCS_STRUKURRF.
READTABLECUST_INFO_TABWITHKEYKUNNR=BILL_DOCS_STRUKUNAG
INTOCUST_INFO_STRU."theREADoperationwillsetSYTABIXtozero
SRL_NO=SRL_NO+1.
WRITE:/5(5)SRL_NO,BILL_DOCS_STRUVBELN,BILL_DOCS_STRUFKDAT,
BILL_DOCS_STRUKUNAG,CUST_INFO_STRUNAME1,
CUST_INFO_STRUORT01,(17)BILL_DOCS_STRUNETWR.
TOTAL=TOTAL+BILL_DOCS_STRUNETWR.
ENDLOOP.
********************************
ENDOFSELECTION.
SKIP1.
WRITE:/(17)TOTALUNDERBILL_DOCS_STRUNETWR.

ObservethefactthatyoucannotusethesystemfieldSYTABIXfora
serialnumber.WhenyouareatthestatementnexttotheLOOP
AT...statement(LOOPATisoperatingonastandardtable/indexed
table),thesystemfieldSYTABIXwillcontainthefetchedrownumber.
ButafterthestatementREAD...WITHKEY...isexecuted(READ...WITH
KEY...isoperatingonahashed/nonindexedtable),thesystemfieldSY
TABIXissettozero.Recallthatforaqhashedtable,thesystemfieldSY
TABIXisinoperative.
YoucouldhavesavedaSYTABIXvalueinanotherdeclaredvariable
beforetheREAD...WITHKEY...statementandoutputthisvariableasa
serialnumber.Youcannotavoidadeclaredvariabletooutputaserial
number.
Theoutputwillbeidenticaltotheonegeneratedbyyourearlierprogram
YCL_CH06_ITAB01.Theoutputwillappearlikethis:

Figure623.OutputofProgramYCL_CH06_ITAB08

Figure624.OutputOfProgramYCL_CH06_ITAB08Grand
Totals

HandsOnExercise:INSERT...INDEX...(InsertaRowata

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

26/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

SpecifiedRowPosition)
Thisstatementcanbeusedtoinsertarowataspecifiedrowpositionand
canbeusedforindexedtables,thatis,standardandsortedtables,though
forsortedtables,itisnotveryadvisable.Thesortedtablerowshavetobe
intheascendingorderofthekeyfields.SointhisformofINSERT
statement,therowbeinginsertedintoasortedtablemustfitinthatrow
positionastomaintaintheascendingorderkeyvalues.
Thesyntaxofthisstatementis:

INSERT<structurename>INTO<internaltablename>
INDEX<indexdataobject>

Thedatafromthe<structurename>willgetinsertedintherowposition
specifiedby<indexdataobject>.Therowexistinginthatrowposition
andbeyond,ifany,areshiftedonerowpositionahead.Forinstance,if
thereare10rowsinatable,andyouinsertarowatrowposition5,the
rowexistingin5thpositionpriortotheINSERTstatementwillbeshifted
tothe6throwpositionandsoonwiththe10throwpriortotheINSERT
statementshiftedtothe11throwposition.
IftheINSERTissuccessful,thesystemfieldSYTABIXissettotherow
numbervalueoftheinsertedrowthesystemfieldSYSUBRCissetto
zero.
IftheINSERTisafailure,therowinsertioncannottakeplacebecause:
1. Itisdisruptingtheascendingorderstateofthesortedtable.
2. Itisattemptingtocreateduplicatekeyvaluerowsinasortedtable
withUNIQUEKEY.
3. The<indexdataobject>LT1.
4. The<indexdataobject>GTcurrentnumberofrows+1.For
instance,ifatableiscontaining10rows,youcanassigna
maximumvalueof11to<indexdataobject>.Youcannotassigna
value>11.Thesystemwillnotbeabletoinsertarowinthat
position.
InthiscaseofINSERTfailure,thesystemfieldSYTABIXissettozero
andthesystemfieldSYSUBRCissettononzero.
Asourceprogramofahandsonexercisewithastandardtableto
highlightthisfeature:

REPORTYCL_CH06_ITAB09.
***************************************
*InternalTablesINSERT..INDEX..**
***************************************
********************************************
*declarestructureTCURT,internaltable**
*ofthisstructure**
***
*inputINSERTrownumberPARAMETERS**
***
*loadinternaltablewithdatafrom**
*databasetableTCURTforcurrencycode**
*startingwith'I'WHEREWAERSLIKE**
*'I%'.**
***
*LOOP...ENDLOOP.outputfrominternal**
*tableoutput:preinsert**
***
*INSERTTCURTINTOCURR_TABindexREC_NO**
***
*ifSYSUNRC=0LOOP..ENDLOOPoutput**
*frominternaltable:postinsert**
*else**
*outputerror**
********************************************
TABLESTCURT."currencydescriptiontexttable
DATA:CURR_TABTYPESTANDARDTABLEOFTCURT.
PARAMETERS:REC_NO(2)TYPENDEFAULT5.
STARTOFSELECTION.
SELECT*FROMTCURTINTOTABLECURR_TAB
WHERESPRAS='E'ANDWAERSLIKE'I%'."currencycodesstarting
"withI
WRITE:/5'PreInsertion:'.
LOOPATCURR_TABINTOTCURT.
WRITE:/5(2)SYTABIX,TCURTWAERS,TCURTLTEXT.
ENDLOOP.
TCURT=SPACE."initialstructureTCURT
TCURTWAERS='IJK'.
TCURTLTEXT='DUMMYCURRENCY'.
INSERTTCURTINTOCURR_TABINDEXREC_NO.
IFSYSUBRC=0.
SKIP1.
WRITE:/5'PostInsertion:'.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

27/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

LOOPATCURR_TABINTOTCURT.
WRITE:/5(2)SYTABIX,TCURTWAERS,TCURTLTEXT.
ENDLOOP.
ELSE.
SKIP1.
FORMATINVERSECOLORCOL_NEGATIVE.
WRITE:/5'ErrorInsertingRowNo.',(2)REC_NO.
FORMATRESET.
ENDIF.

TheoutputsofprogramYCL_CH06_ITAB09willlooklikethis:

Figure625.OutputOfProgramYCL_CH06_ITAB09Row
INSERTED

Youinsertedarowatrowposition5.Therowexistinginthisposition
priortoINSERTwasINRIndianRupee,andthefollowingrowshave
beenpushedaheadbyonerow.
Inthenextinstance,youtriedtoINSERTarowatrowposition11.

Figure626.OutputofProgramYCL_CH06_ITAB09Row
INSERTError

ThenumberofrowsexistingpriortoINSERTis9.Thelastrowposition
whereyoucansuccessfullyINSERTarowis10.Sothishasresultedinan
errorcondition.
ThereisavariationofthisINSERTstatementwherebyyoucaninsert
multiplerowsfromasourceinternaltabletoadestinationinternaltable.
NonIndexINSERTStatement
ThestatementSyntaxis:
INSERT<structurename>INTOTABLE<internaltablename>.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

28/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

ThisformofINSERTstatementisgenerallyusedtobuildsortedand
hashedtablesrowbyrow.Ifyouusethisstatementforastandardtable,it
operatesasanAPPENDstatement.Whenyouaretransferringdatafrom
adatabasetabletoaninternaltable:Inthecaseofthesortedtables,the
rowsareenteredintotheinternaltableintheascendingorderofthekey
fieldsInthecaseofhashedtablesrowsareinsertedintotheinternal
tablebythehashadministrationaccordingtoitskeyvalues.Thesame
principlesapplywhenyouinsertonerowatatimefromthestructureto
theinternaltableoftypesortedorhashed.
ThereisavariationofthisINSERTstatementwherebyyoucaninsert
multiplerowsfromasourceinternaltabletoadestinationinternaltable.
DeleteDatafromInternalTables
Sometimes,youneedtodeletearoworrowsfromaninternaltable.You
usetheDELETEstatementtodothis.
DELETESingleRows
ThesyntaxtoDELETEsinglerowsis:

DELETE{TABLE<internaltablename><keyvalues>}|
{<internaltablename>[INDEX<dataobject>]}.

Youcandeletearowbysupplyingthekeyvaluesforsortedorhashed
tables.
Youcandeletearowbysupplyingtheindexorrownumberforindexed
tables.
WhenaDELETEwithindexstatementislocatedinsidea
LOOP...ENDLOOPconstruct,theINDEXspecificationisoptional.
Implicitlyitwilldeletethecurrentlyfetchedrow.
DELETEMultipleRows
Thesyntaxfordeletingmultiplerowsfromaninternalstatementis:
DELETE<internaltablename>[FROM<startindex>][TO<endindex>
[WHERE<condition>].

Alltherowsstartingfrom<startindex>andtill<endindex>satisfying
the<condition>willbedeleted.
HandsOnExercise:DeleteAdjacentDuplicates
Scenario
Supposeyouwanttohavealistofcustomerswithbillingdocuments
againstthem.Thisisjustasimplelistcontainingcustomercode,name,
andcityforcustomerswithbillingdocuments.
RecallthedatabaseviewyoucreatedwiththetablesKNA1andVBRK.
Thiscontainstheinformationyouwantbutnotintheexactfashion.A
customerhavingnnumberofbillingdocumentswillhavennumberof
rowsinthisdatabaseview.Inouroutputyouwantthisnnumberofrows
tobereducedtoonerow.Youcanreducethennumberofrowstoone
rowwiththestatementDELETEADJACENTDUPLICATES.This
statement,onspecificationoffields,deletesallduplicatesandretains
onerowforonevalueofthespecifiedfields(equivalentineffecttoSQL
SELECTDISTINCT...).Theprerequisiteforthisisthattheinternaltable
shouldbesortedintheascendingorderofthefieldsonwhichyouwantto
deleteduplicates.Thesystemwillnotcheckwhetherthetableisinthe
sortedorder.
Asusual,youwillprovidefortheoutputtobeproducedforaspecified
companycode.
Thesyntaxofthisstatementis:

DELETEADJACENTDUPLICATESFROM<internaltablename>
[COMPARING{<field1>[<field2>...]}|{ALLFIELDS}].

YouroutputbodylayoutisshowninTable65.
Table65.OutputBodyLayout

Thesourceprogram:

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

29/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

REPORTYCL_CH06_ITAB10LINESIZE95LINECOUNT60
NOSTANDARDPAGEHEADING.
**************************************************************************
*DELETEADJACENTDUPLICATESListofCustomersWithBillingDocuments**
**************************************************************************
**************************************************
*declarestructureandinternaltable**
***
*inputcompanycodePARAMETERS**
***
*loadinternaltableSELECTetc.**
***
*sortinternaltableBYKUNNR**
*DELETEADJACENTDUPLICATES...COMPARINGKUNNR**
***
*LOOPAT...WRITE..ENDLOOP.**
**************************************************
DATA:BEGINOFCUST_STRU,
KUNNRTYPEKNA1KUNNR,
NAME1TYPEKNA1NAME1,
ORT01TYPEKNA1ORT01,
ENDOFCUST_STRU,
CUST_TABLIKESTANDARDTABLEOFCUST_STRU,
BUTXTTYPET001BUTXT.
*************************************************
PARAMETERSCCODETYPEVBRKBUKRSDEFAULT3000VALUECHECK.
TOPOFPAGE.
WRITE:/5TEXT001NOGAP,CCODENOGAP,'/'NOGAP,BUTXT,92(2)SYPAGNO.
WRITE:/5(88)SYULINE.
WRITE:/5TEXT002,11TEXT003,22TEXT004,58TEXT005.
WRITE:/6TEXT006,13TEXT007.
WRITE:/5(88)SYULINE.
STARTOFSELECTION.
SELECTSINGLEBUTXTFROMT001INTO(BUTXT)WHEREBUKRS=CCODE.
SELECTKUNNRNAME1ORT01FROMYCL_CH05_VBRKKNA
INTOTABLECUST_TAB
WHEREBUKRS=CCODE.
SORTCUST_TABBYKUNNR.
DELETEADJACENTDUPLICATESFROMCUST_TABCOMPARINGKUNNR.
**************************************************************
LOOPATCUST_TABINTOCUST_STRU.
WRITE:/5(4)SYTABIX,CUST_STRUKUNNRUSINGNOEDITMASK,
CUST_STRUNAME1,CUST_STRUORT01.
ENDLOOP.

Createtextsymbolsandactivate.TheywillappearlikeFigure627.

Figure627.ProgramYCL_CH06_ITAB10TextSymbols

Theoutputwillappearlikethis:

Figure628.ProgramYCL_CH06_ITAB10Output

MODIFYStatementUpdate/ChangeExistingRowsinInternal
Tables
YoucanupdateorchangerowsininternaltableswiththeMODIFY
statement.Youcanupdateoneormultiplerowswiththisstatement.
MODIFYStatementUpdateorChangeaSingleRow
1. ThesyntaxoftheMODIFYstatementtoupdateasinglerowby
supplyingtherownumberofatableis:
MODIFY<internaltablename>INDEX<dataobjectname>FROM
<structurename>[TRANSPORTING<field1>[field2..]].

1. The<dataobjectname>istherownumbertobeupdated.It

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

30/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

canbealiteral/constant/variable.Ifthisnumberisa
nonexistentrow,anerrorconditionarises.
2. IftheTRANSPORTINGoptionisnotspecified,thecomplete
datafromthe<structurename>willbewrittentotherow
numberspecifiedwiththe<dataobjectname>intheinternal
table.
3. IftheTRANSPORTINGoptionisspecified,onlythedataof
thefieldsspecifiedwithTRANSPORTINGarewrittentothe
rownumberspecifiedwiththe<dataobjectname>inthe
internaltable.
4. IfyougivethisstatementwithinaLOOP...ENDLOOP
constructandyouwanttomodifythecurrentrowfetchedthe
INDEX<dataobject>canbedropped.Therownumberin
thiscaseisimplicit.
5. Thissyntaxworksforindexedtables.

2. ThesyntaxoftheMODIFYstatementtoupdateasinglerowby
supplyingkeyfieldvaluesofatableis:
MODIFYTABLE<internaltablename>FROM<structurename>[TRANSPORTING<field1>[field2..]].

1. Datawillbeupdatedforrowslocatedthroughthekeyfield
valuesof<structurename>.Ifarowisnotlocatableforthe
keyfieldvalues,anerrorconditionarises.
2. IftheTRANSPORTINGoptionisnotspecified,thecomplete
datafromthe<structurename>willbewrittentotherow
correspondingtothekeyfieldvaluesintheinternaltable.
3. IftheTRANSPORTINGoptionisspecified,onlythedataof
thefieldsspecifiedwithTRANSPORTINGarewrittentothe
rowcorrespondingtothekeyfieldvaluesintheinternal
table.

MODIFYStatementUpdateorChangeMultipleRows
ThesyntaxoftheMODIFYstatementtoupdateorchangemultiplerows
is:

MODIFY<internaltablename>FROM<structurename>
TRANSPORTING<field1>[field2>..]WHERE<condition>.

Alltherowsintheinternaltablefulfillingthe<condition>willbe
updated.
HandsOnExercise:MODIFYSingleRow
Asitwasenumerated,singlerowscanbeupdatedthrough(a)The
INDEX,thatis,supplytherownumbertotheMODIFYstatementandthe
suppliedrownumberifitexistswillbeupdatedwiththedatafromthe
structure(b)Keyfieldvalues.Assignthekeyfieldsofthestructurewith
theappropriatevalues,issuetheMODIFYstatementandtheMODIFY
statementwilllocatetherowcorrespondingthekeyfieldvaluesofthe
structureandwillupdatethisrowifitexistsfromthestructure.
ThesetwoformsoftheMODIFYstatementhavebeenusedtoupdate
misspelleddataloadedfromthedatabasetableT005Uintoasorted
internaltable.TheT005Utablecontainstextsofthe
states/provinces/regionsofallthecountries.
Refertothecommentlinesofthesourceprogramforadetailed
descriptionoftheexercise.
Thesourceprogramis:
REPORTYCL_CH06_ITAB11.
*******************************************************
*InternalTablesMODIFYstatementonSortedTable**
*(Singlerow)**
*******************************************************
***********************************************************
*tableT005Uisatexttable.itcontainsthestate/**
*region/provincetextsofallcountries.likefor**
*exampleitcontainsthetextsofalltheindianstates**
*andunionterritories.thetextsareinallthe**
*languagessupported.theprimarykeyfieldsofthis**
*tableare**
*MANDTclientcode**
*SPRASlanguagekeycode**
*LAND1countrycode**
*BLANDstate/region/provincecode**
***
*thetextfieldisBEZEI**
***
*forindia(LAND1='IN'),languageenglish(language**
*keycodeSPRAS='E'),thestatecode'01':thestate**
*hasbeenmissspelt.itis'AndraPradesh'insteadof**
*being'AndhraPradesh'(letterhismissinginfirst**
*word)**
***
*similarlyforBLAND='26'thetextis'Andamanund**

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

31/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

*Nico.In.'insteadof'AndamanandNico.In.'('and'has**
*missspeltas'und'**
***
*youwillloadtextsofindianstatesinenglishintoa**
*sortedinternaltablefromdatabasetableT005U.**
*(WHERESPRAS='E'ANDLAND1='IN')**
*thissortedtabledefinedkeywillbeMANDT,SPRAS,**
*LAND1,BLAND**
***
*youwillassignthestructuretextfield:**
*BEZEI='AndhraPradesh'**
***
*youwillissuetheMODIFYstatementwithINDEX1and**
*TRANSPORTINGBEZEIi.e.onlyupdatefieldBEZEI.**
***
*thesystemwilllocatetherowintheinternal**
*sortedtablethrutheINDEX1(rownumber1)**
*itwillupdatethefieldBEZEIfromthevalueinthe**
*structurefieldintotheBEZEIfieldinthelocated**
*row.**
*thisisMODIFYwithINDEX**
***
***
*youwillassignthestructureprimarykeyfieldsthe**
*values:**
*MANDT=800,SPRAS='E',LAND1='IN',BLAND='26'**
***
*youwillassignthestructuretextfield:**
*BEZEI='AndamanandNico.In.**
***
*youwillissuetheMODIFYstatementwithTRANSPORTING**
*BEZEIi.e.onlyupdatefieldBEZEI.**
***
*thesystemwilllocatetherowintheinternal**
*sortedtablethruthevaluesinstructurekeyfields**
*itwillupdatethefieldBEZEIfromthevalueinthe**
*structurefieldintotheBEZEIfieldinthelocated**
*row.**
*thisisMODIFYwithkey**
***
***
*thisishappeningonlyintheinternaltable.no**
*changesareoccurringinthedatabasetableT005U**
***********************************************************
TABLEST005U.
DATA:STATES_TABLIKESORTEDTABLEOFT005UWITHUNIQUEKEY
MANDTSPRASLAND1BLAND.
STARTOFSELECTION.
SELECT*FROMT005UINTOTABLESTATES_TABWHERE
SPRAS='E'ANDLAND1='IN'.
WRITE:/5'PreMODIFYOutput(OnlyStatesStartingWithA)'.
SKIP.
LOOPATSTATES_TABINTOT005UWHEREBEZEICP'A*'.
WRITE:/5T005UBLAND,T005UBEZEI.
ENDLOOP.
*T005UMANDT=800.
*T005USPRAS='E'.
*T005ULAND1='IN'.
*T005UBLAND='01'.
T005UBEZEI='AndhraPradesh'.
MODIFYSTATES_TABFROMT005UINDEX1TRANSPORTINGBEZEI.
T005UMANDT=800.
T005USPRAS='E'.
T005ULAND1='IN'.
T005UBLAND='26'.
T005UBEZEI='AndamanandNico.In.'.
MODIFYTABLESTATES_TABFROMT005UTRANSPORTINGBEZEI.
SKIP3.
WRITE:/5'PostMODIFYOutput(OnlyStatesStartingWithA)'.
SKIP.
LOOPATSTATES_TABINTOT005UWHEREBEZEICP'A*'.
WRITE:/5T005UBLAND,T005UBEZEI.
ENDLOOP.

IntheLOOPstatement,youhavegivenaWHEREcondition.Youwant
tofilteroutthefieldBEZEIvaluesstartingwithA.Youhavegiventhe
stringcomparisonoperatorCP(containspattern).RefertoChapter4.It
isequivalenttogivingLIKEA%inaSQLstatement.The*(asterisk)is
forpattern,justlike%inaSQLstatements.
Theoutputwillbelikethis:

Figure629.ProgramYCL_CH06_ITAB11Output

HandsOnExercise:MODIFYMultipleRows
AshasbeenspelledoutinII,youcanupdatemultiplerowswiththe

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

32/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

MODIFYstatement.
YouareusingthedatabasetableLFA1supplier/vendorprimarytable.
ItisonparallellinesofthecustomerprimarytableKNA1.Youare
loadingafewfieldsofthistableintoaninternaltable.ThefieldANRED
containsblanksforsomerows.WherethevalueforABREDisblank,you
arereplacingitwithMessrs.usingtheMODIFYstatement.The
internaltableisoutputbeforeMODIFYandafterMODIFY.
Thesourceprogram:
REPORTYCL_CH06_ITAB12LINESIZE110LINECOUNT60
NOSTANDARDPAGEHEADING.
*************************************************************
*InternalTablesUpdate/Change(MODIFY)MultipleRows**
*************************************************************
*****************************************************************
*databasetableLFA1issupplier/vendorprimarytable.**
*thetablehasafieldANREDwhichcontainsthetitlefor**
*theenterpriselike'Company','Firma'etc.**
*(thesamefieldisthereincustomerprimarytableKNA1)**
***
*ManyoftherowshaveblankinthisfieldANRED**
*youwillloadthefieldsLIFNR(suppliercode),ANRED,NAME1,**
*ORT01intoaninternaltable.youwillreplacetheblank**
*ANREDvalueswith'Messrs.'withtheMODIFYstatement**
*outputtheinternaltablebeforetheMODIFYstatementand**
*aftertheMODIFYstatement**
*****************************************************************
DATA:BEGINOFVENDOR_STRU,
LIFNRTYPELFA1LIFNR,
ANREDTYPELFA1ANRED,
NAME1TYPELFA1NAME1,
ORT01TYPELFA1ORT01,
ENDOFVENDOR_STRU,
VENDOR_TABLIKESTANDARDTABLEOFVENDOR_STRU,
STRNGTYPESTRING.
****************************************************
TOPOFPAGE.
WRITE:/5TEXT001,STRNG,104(3)SYPAGNO.
WRITE:/5(102)SYULINE.
WRITE:/5TEXT002,12TEXT003,23TEXT004,39TEXT005,75TEXT006.
WRITE:/5TEXT007,13TEXT008.
WRITE:/5(102)SYULINE.
****************************************************
STARTOFSELECTION.
SELECTLIFNRANREDNAME1ORT01FROMLFA1INTOTABLEVENDOR_TAB
UPTO100ROWS.
SORTVENDOR_TABBYLIFNR.
STRNG=TEXT009.
LOOPATVENDOR_TABINTOVENDOR_STRU.
WRITE:/5(4)SYTABIX,VENDOR_STRULIFNRUSINGNOEDITMASK,
VENDOR_STRUANRED,VENDOR_STRUNAME1,VENDOR_STRUORT01.
ENDLOOP.
VENDOR_STRUANRED='Messrs.'.
MODIFYVENDOR_TABFROMVENDOR_STRUTRANSPORTINGANRED
WHEREANRED=''.
STRNG=TEXT010.
NEWPAGE."startpostMODIFYonanewpage
LOOPATVENDOR_TABINTOVENDOR_STRU.
WRITE:/5(4)SYTABIX,VENDOR_STRULIFNRUSINGNOEDITMASK,
VENDOR_STRUANRED,VENDOR_STRUNAME1,VENDOR_STRUORT01.
ENDLOOP.

Thetextsymbols:

Figure630.ProgramYCL_CH06_ITAB12TextSymbols

Theoutput:

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

33/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

Figure631.ProgramYCL_CH06_ITAB12Output[Pre
MODIFY]

Figure632.ProgramYCL_CH06_ITAB12Output[Post
MODIFY]

HandsOnExercise:DESCRIBETABLEStatement,Function:
LINES()
YoucanknowtheattributesofaninternaltableusingtheDESCRIBE
TABLEstatement.Youcanascertainthenumberofrowsintheinternal
table,thetabletype,thenumbergivenwiththeclauseINITIALSIZE.
ThesyntaxoftheDESCRIBETABLEis:
DESCRIBETABLE<internaltablename>[LINES<linesvariablename]
[OCCURS<occursvariablename][KIND<tablekindvariablename>].

Afterthestatementisissued,thesystemfieldSYTFILLwill
containthenumberofrowsoftheinternaltableonwhichthe
DESCRIBETABLEstatementwasoperatedupon.
Ifyouwantthenumberofrowsoftheinternaltableinyour
declaredvariable,youcanusetheoptionalLINES<linesvariable
name>.
IfyouwantthenumberspecifiedwiththeINITIALSIZEor
OCCURSclause,youcangivetheoptionaladditionOCCURS
<occursvariablename>.
IfyouwanttheinternaltableTYPE:standard,sorted,orhashed
youcangivetheoptionaladditionKIND<tablekindvariable
name>.Thisadditionreturnsaonecharacterinternaltabletype:
Tforstandard,Sforsorted,orHforhashed.
AsanalternativetotheDESCRIBETABLE..statement,afunctionis
availabletodeterminethenumberofrowsinaninternaltable:

<noofrowsvariable>=LINES(internaltablename).

ThefunctionLINES(itab)isthepreferredwayofascertainingthenumber
ofrowsinaninternaltableoverthestatementDESCRIBE
TABLE...LINES...
Thesefeatureshavebeenhighlightedinthehandsonexerciseprogram.
Forthishandsonexercise,ahashedtableYCL_CH06_TCURT_TABhas
beendefinedintheDDICwithlinetypeTCURTandINITIALSIZE50,
andUNIQUEKEYFIELDS:MANDT,SPRAS,andWAERS.Thisinternal
tableisloadedfromcurrencytextdatabasetableTCURT.
Thesourceprogramis:
REPORTYCL_CH06_ITAB13.
*************************************
*InternalTablesDESCRIBETABLE**
*Function:<var>=LINES(itab).**
*************************************
*************************************************
*DESCRIBETABLEstatementreturns:**
***
*(1)theinternaltableTYPEHforhashed**
*/KINDSforsorted**
*Tforstandard**
*thetableTYPEisreturnedbyusingthe**
*addition/clauseKINDfollowedbythe**
*variablename**
***
*(2)thenumberrows/linesintheinternal**
*table.youcangetthisinfo**

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

34/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

*(a)inyourdefinedvariablebyusing**
*theaddition/clauseLINESfollowed**
*byyourvariablename**
*(b)itisautomaticallyloadedintothe**
*systemfieldSYTFILL.another**
*DESCRIBEstatementwilloverwrite**
*thissystemfield**
***
*(3)INITIALSIZE:returnedbyusingthe**
*addition/clauseOCCURSfollowedbythe**
*variablename**
***
*Thenumberofrows/linesintheinternal**
*tablearealsodeterminedbythefunction**
*LINES().Togetthenumberofrows/lines**
*inyourdefinedvariableusingthisfunction**
*<variable>=LINES(<internaltablename>).**
***
*************************************************
DATA:INT_TABLETYPEYCL_CH06_TCURT_TAB,
"referringtoDDICtableTYPE
TABLE_TYP(1)TYPEC,
TABLE_LINES1TYPESYTFILL,"SYTFILLisTYPEI
TABLE_LINES2TYPESYTFILL,
INIT_SIZE(2)TYPEN.
**************************************************
STARTOFSELECTION.
SELECT*FROMTCURTINTOTABLEINT_TABLE.
DESCRIBETABLEINT_TABLELINESTABLE_LINES1
KINDTABLE_TYPOCCURSINIT_SIZE.
TABLE_LINES2=LINES(INT_TABLE)."functiontodeterminetablelines
SKIP5.
WRITE:/5'TABLETYPE''H''/''S''/''T'':',TABLE_TYP,
/5'TABLEROWS/LINESDESCRIBE:',(4)TABLE_LINES1,
/5'TABLEROW/LINESLINES():',(4)TABLE_LINES2,
/5'SYTFILL:',(4)SYTFILL,
/5'INITIALSIZE:',INIT_SIZE.

Theoutput:

Figure633.ProgramYCL_CH06_ITAB13Output

HandsOnExercise:ProduceMultilevelSummaryUsingInternal
TableControlLevelProcessing
Theinternaltablefeatureofcontrollevelprocessingfacilitateseasy
productionofmultilevelsummarylists.Youhadproducedsinglelevel
summarylistsusingtheCOLLECTstatementinprograms
YCL_CH06_ITAB05andYCL_CH06_ITAB06.Boththeprograms
producedcustomerwisesalessummary.Therewasonesummarizing
entity:thecustomer.Youcanproducesinglelevelsummaryoutputs
withouttheCOLLECTstatement.Thatwouldhaveentailedextracoding.
Similarly,thecontrollevelprocessinghelpscutdownoncoding.
Scenario
Yourequireatwolevelsummarylistinvolvingtheentities:customer
andmaterial.Intechnicalterms,ourfieldsofsummarizationare
KUNNRandMATNR.Theoutputshouldlistthesaleofdifferent
materialsforeachcustomer.
Averyroughlayout:

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

35/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

Observethatundereachcustomerthesalestotalofeachmaterialforthe
customerislisted.
Whenallthematerialsforthecustomerareexhaustedthetotalforthe
customerisoutputtotherightofthetotalsforeachmaterial.
Similarly,whenallthecustomersareexhausted,agrandtotalisoutputto
therightofthetotalsforeachcustomer.
Anoutputwouldgenerallybeproposedbytheenduse.Alessrough
outputlayout:

Inthislayout,youhavenotbeenabletoaccommodatethegrandtotalon
theextremerightduetolackofhorizontalspace.Soitisimplicit.
InputDataIdentification
Youmustidentifythetablesandfieldsrequiredtoproducethisoutput.
Thetableofthebasicdataalwaysshouldbeidentified.Youneedmaterial
wisesalesbasicdata.Thisisavailableinthebillingdocumentitem
databasetableVBRP.Inthetabletheamountforeachmaterialoritemis
availableasaseparaterow.ThefieldsrequiredbyyouinVBRPtable
are:
MATNRMaterialCodelength18
NETWRNetValueofMaterial/IteminDocumentCurrency

NotethatmaterialcodeMATNRis18characters.TheNETWRinVBRP
shouldbedistinguishedfromtheNETWRofVBRK.InVBRP,thisisthe
netvalueofeachmaterial.Ifinabillingdocument,10boltsaresoldfor
$1000,NETWRofthatrowinVBRPwillcontainthis.Ifinthesame
billingdocumentthereisonemorematerialoritem5nutsfor$250,this
willbeanotherrowinVBRPandthefieldNETWRinthisrowwill
contain$250.IntheVBRKtable(billingdocumentheader),thebilling
documentrowtowhichthesematerialsoritemsbelong,theNETWRfield
willcontainatotalofthesetwomaterialsoritems(i.e.,1000+250=
$1250.ThedocumentcurrencyofthisbillingdocumentwasUSDollar
denotedbyUSD.Notethatinthedatamodel,VBRKistheprimarytable
andVBRPthesecondary.TheyarerelatedthroughthefieldsMANDT
andVBELN.
Earlier,inyourcustomerwisesalessummary,youwereusingthe
NETWRofthetableVBRK.Youwantedacustomerwisesummaryand
werenotbotheredwithindividualmaterials/items.
Eachbillingdocumentofacompanycodecanhaveadifferentcurrency.
Supposethecompanycodetowhichthisbillingdocumentbelongshasthe
operatingcurrencyasIndianRupeedenotedasINR.Thenforyour
summarylistpurposes,youneedtoconverttheamountsfromUSDto
INR.Similarlyforeveryamount,youneedtoconverttheamountsfrom
documentcurrencytothecompanycodecurrency.Soyouneedthe
exchangerate.TheexchangeratefieldKURRFisavailableinthetable
VBRK:
KURRFintableVBRKExchangeRate

Youneedmaterialdescriptions.Thematerialdescriptionsare
maintainedinmultiplelanguagesinthetexttableMAKT.
MAKTXintableMAKTMaterialDescription

Youneedacustomercodeandcustomername.Theseareavailablein
tableKNA1:
KUNNRCustomerCode
NAME1CustomerName

ThetableKNA1cannotbelinkedtotableVBRPdirectly.Thereareno
commonfields.TheyaretobelinkedthroughthetableVBRKthat

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

36/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

containscustomercodefieldKUNAG.YouareaccessingthefieldKURRF
fromVBRK.
Soyouneedtoretrievedatafromfourdatabasetables:
VBRPBillingDocumentsItem
MAKTMaterialDescriptions
VBRKBillingDocumentHeader
KNA1CustomerPrimary

Youwillcreateadatabaseviewconsistingofthesefourtablesandgather
allthedatainoneDDICobject.
Yourdatamodelfortheviewis:

Figure634.DataModelDatabaseView
YCL_CH06_CM_SALE

Sincethedatabaseviewusesaninnerjoin,positioningatableontheleft
orrightdoesnotmatter.YouaretreatingthetableVBRPatthetopofthe
hierarchybecauseitiscontainingthebasicdata.
DatabaseView
Thedatabaseviewtablecolumnandjoinconditionscolumnswillbelike
this:

KNA1
VBRKVBRPMANDT=MAKTMANDT
MAKTVBRPMATNR=MAKTMATNR
VBRPVBRPMANDT=VBRKMANDT
VBRPVBELN=VBRKVBELN
VBRKMANDT=KNA1MANDT
VBRKKUNAG=KNA1KUNNR

Thedatabaseviewfieldlistwillbelikethis:
MANDTVBRPMANDT
VBELNVBRPVBELN
POSNRVBRPPOSNR
SPRASMAKTSPRAS
KUNNRKNA1KUNNR
MATNRVBRPMATNR
NETWRVBRPNETWR
MAKTXMAKTMAKTX
BUKRSVBRKBUKRS
KURRFVBRKKURRF
WAERKVBRKWAERK
NAME1KNA1NAME1

Thedatabaseviewselectionconditionsshouldbelikethis:
MAKTSPRASEQ'E'

Youneedtohavethiscondition,orelsetheviewwillhavematerial
descriptionsinalltheinstalledlanguages.Youarefilteringoutthe
descriptionsinEnglish.
CreateadatabaseviewYCL_CH06_CM_SALEwiththesespecifications.
Check,activateandaudittheview.
OutputMainBodyLayout
Theoutputbodylayoutintermsoffields,tableorigins,andcolumn
positionsis:
Table66.Customer,MaterialWiseSalesSummaryofaCompany
Code:OutputLayout

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

37/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

ControlLevels
Thewholeprocessofamultilevelsummarizationofdatatakesplace
withintheLOOP...ENDLOOP.
Therearethehierarchicalcontrollevelstatementscorrespondingor
mappingtoyoursummarizationlevelsorfields.Likeinyourscenario,
yoursummarizationfieldsareKUNNR(customercode)andMATNR
(materialcode).Thecontrolwilljumptothesecontrollevelstatements
dependingonconditionsarisingwiththeprocessingofdata.Acontrol
levelstatementblockstartswiththekeywordATandendsorterminates
withthekeywordENDAT.
Youshouldensurethatyourtableissortedintheascendingorderof
summarizationorcontrolfields,thatis,KUNNRorMATNR.
Thecontrollevelstatementsareasfollows:
ATFIRST
ATNEW<controlfield>
ATENDOF<controlfield>
ONCHANGE<controlfield>
ATLAST
WiththeLOOP...ENDLOOP,thecontrollevelstatementswillappear
likethis:

LOOPAT<internaltablename>INTO<structurename>.
ATFIRST.
<statementblock>.
ENDAT
ATNEW<firstlevelofcontrolfield>.
<statementblock>.
ENDAT.
ATNEW<secondlevelofcontrolfield>.
<statementblock>.
ENDAT.
......"moreATNEWcontrolsifany
......"moreATENDOFcontrolsifany
ATENDOF<secondlevelofcontrolfield>.
<statementblock>.
ENDAT.
ATENDOF<firstlevelofcontrolfield>.
<statementblock>.
ENDAT.
ATLAST.
<statementblock>.
ENDAT.
ENDLOOP.

Theorderorhierarchyofthesecontrollevelstatementsistobe
maintainedasshownintheprecedingpseudocodeasastandard
practice.Youmaynothaveanyactiontobetakenforaparticularcontrol
levelandcanomitit.
NotethatfortheATNEWcontrollevels,theorderisthesameasthe
summarizationlevels,thatis,ATNEW<firstlevelofcontrolor
summarization>,ATNEW<secondlevelofcontrolorsummarization>
andsooniftherearemorethantwolevelsofsummarization.
TheorderofATENDOFcontrollevelsisthereverseoftheorderofAT
NEWcontrollevels.StartingwithATENDOF<secondlevelofcontrolor
summarization>,nexttheATENDOF<firstlevelofcontrolor
summarization>.
ThecontrollevelATFIRSTisatthetopandthecontrollevelATLASTat
thebottom.
ThecontrollevelstatementscannotbeusedinLOOP...ENDLOOPwith
WHEREand/orFROMandTO.Also,thetableshouldnotbemodified
duringtheLOOP...ENDLOOP.
ATFIRST:Afterthefirstrowisfetchedfromtheinternaltable(firstpass
oftheloop),thecontrolwilljumptothecontrollevelATFIRST.Ifyou
havesomeactiontobeperformedforthiscontrollevel,youneedtoput
thiscontrollevelelseyoucanomitit.Thisappliestoallcontrollevels.
ATNEW:Everytimeanewvalueof<secondlevelofcontrolfield>or
<firstlevelofcontrolfield>isfetched,controlwilljumptothiscontrol
level.
Incaseofanewvalueof<firstlevelofcontrolfield>,itfirstjumpstothe
controllevelof<firstlevelofcontrolfield>followedbyajumpto
<secondlevelofcontrolfield>.
Incasewhereanewvalueof<secondlevelofcontrolfield>,itonly

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

38/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

jumpsto<secondlevelofcontrolfield>.
ATENDOF:Everytimealltherowsforaparticularvalueof<second
levelofcontrolfield>or<firstlevelofcontrolfield>havebeenfetched,
controlwilljumptothiscontrollevel.
Inthecasewhereallrowsofaparticularvalueof<firstlevelofcontrol
field>havebeenfetched,itfirstjumpstothecontrollevelof<second
levelofcontrolfield>followedbyajumpto<firstlevelofcontrolfield>.
Inthecasewhereallrowsofaparticularvalueof<secondlevelofcontrol
field>havebeenfetched,itonlyjumpsto<secondlevelofcontrolfield>.
ONCHANGEOF:ThisissimilartoATNEWcontrol.Everytimethereis
achangeofvalueinthefield,controlwilljumptothislevel.Thisisnot
specifiedintheLOOPENDLOOPpseudocode.
ATLAST:Whenalltherowsoftheinternaltablehavebeenfetched,
beforeexitingtheLOOP...ENDLOOP,controlwilljumptothiscontrol
level.
Torecapitulate,youneedtousecontrollevelswithinthe
LOOP...ENDLOOPtobeabletotakeactionforthesituationstriggering
thecontrollevels.Therearethetwoessentialprerequisites:(a)The
controllevelsshouldbeintheordergiveninthepseudocodeasa
standardpractice(b)Theinternaltableshouldbesortedinthe
ascendingorderofthesummarizationorcontrolfields.Thediscussion
hasbeenconductedforthesakeofeasyunderstanding,intermsoftwo
controlfields.Itwouldapplytonnumberofcontrolfields.
MappingApplicationofControlLevelstoScenario
Now,letthesecontrollevelsbemappedtoyouroutputlayout:
Everytimeanewcustomerrowisfetched,youneedtooutputthe
customerinfo,thatis,customercodeandname.Theseareserial
numbers1and2inTable66.SoyoucanuseATNEWKUNNRforthis.
Considertheoutputofsummarylinesforeachmaterialsoldtothis
customer.Amaterialcouldbesoldonce,twice,ornnumberoftimestoa
customer.Thesennumberofrowsofamaterialneedtobesummarized
andatotalistobeoutputalongwithamaterialcodeandmaterial
description.Soyouwantcontrolwhenalltherowsforaparticular
materialunderaparticularcustomerhavebeenfetched.Youcanusethe
ATENDOFMATNRcontrollevel.Yououtputthematerialcode,
description,andtotalamountforamaterial,thatis,serialnumbers3,4,
and5ofTable66.
Whenalltherowsofaparticularcustomerhavebeenfetched,youneedto
outputthetotalforthecustomerappearingtotherightofmaterialwise
total.YoucanusetheATENDOFKUNNR.Thisisserialnumber6of
Table66.
Foryourgrandtotal,youcanusethecontrollevelATLAST.Thisisserial
number7ofTable66.
SUMstatement
Thenextissueishowthetotalswillbebuiltandaccumulatedforthethree
instances:materialwise,customerwise,andthegrandtotal.Alongwith
thecontrollevelfeaturetheSUMstatementisprovided.Thesyntaxof
theSUMstatementis:
SUM.

TheSUMstatementcanonlybegiveninsideaLOOP...ENDLOOP
construct.IfthereisanestingofLOOP...ENDLOOP,theSUMstatement
isnotaccepted.
TheSUMstatementoperatesinthefollowingway:
TheSUMstatementoperatesontypesF,I,andPthatarenumericfields.
Itaccumulatesthenumericfieldsforalltherowsfetchedforaparticular
valueofthecontrolfieldiftheSUMstatementisgivenintheATEND
OF...controlblock.
Itaccumulatesthenumericfieldsforalltherowstobefetchedfora
particularvalueofthecontrolfieldiftheSUMstatementisgiveninthe
ATNEW...controlblock.
Theaccumulatedtotalsareplacedinthenumericfieldsofthestructure.
Youcanusetheaccumulatedcontrol,numericfields,andoutputit,etc.
Toillustratewithanexample,yourinternaltablenameis
SALES_SUM_TABandyourworkarea/structurenameis
SALES_SUM_STRU.Supposesomeofyourdataisasfollows:
MATNRMAKTXNETWR

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

39/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

1234BOLT50000
1234BOLT20000
1234BOLT70000
1234BOLT30000
1235NUT10000
....................
LOOPATSALES_SUM_TABINTOSALES_SUM_TRU.
ATENDOFMATNR.
SUM.
ENDAT.
ENDLOOP.

So,whenthefourrowsofMATNRvalueequalto1234havebeenfetched,
controlwilljumptotheATENDOFMATNR.TheSUMSTATEMENTwill
beexecuted.AftertheexecutionoftheSUMstatement,thefield
SALES_SUM_STRUNETWRwillcontain170000.Now,allthatis
requiredistooutputthisfieldwithMATNRandMAKTX.
Asimilarillustrationcanbegivenforthecustomerwisetotalandthe
grandtotal.
ExtraProcessing
Youneedtotakecareoftwomoreissues.
I.ThefirstissueisrelatedtothefieldNETWRandtheSUMstatement.
TheSUMstatementwilltotaltheNETWRvaluesofindividualrows.So
theindividualrowsintheinternaltablemusthavetheconvertedvalueof
NETWR,thatis,NETWRmultipliedbyKURRF,theexchangeratefield.
ThiswillconvertallthevaluesofNETWRintoonecurrency,the
currencyofthecompanycode(ortheoperatingcurrency).Otherwiseyou
willendupaddingIndianRupee(INR)valuestoUSDollars(USD)
values,ameaninglessexercise.Toincorporatetheseconvertedamounts
intointernaltableindividualrows,youwillrunaLOOP...ENDLOOPin
whichyoufetchonerowfromtheinternaltableintothestructureand
multiplythestructurefields:

SALES_SUM_STRUNETWR=SALES_SUM_STRUNETWR*SALES_SUM_STRUKURRF.

Write/updatethisconvertedamountfromthestructuretotheinternal
tablerowusingtheMODIFYstatement.Thecodewillbelikethis:

LOOPATSALES_SUM_TABINTOSALES_SUM_STRU.
SALES_SUM_STRUNETWR=SALES_SUM_STRUNETWR*SALES_SUM_STRUKURRF.
MODIFYSALES_SUM_TABFROMSALES_SUM_STRUINDEXSYTABIX
TRANSPORTINGNETWR.
ENDLOOP.

ThiswillresultinalltheNETWRvaluesintheinternaltablein
convertedform.
II.Whenthereisajumptothecontrollevels,thenonnumeric,non
controlfieldslikeNAME1andMAKTXarefilledwithnull(outputas*
asterisks).Youneedtooutputthesefields.Sothesefieldsneedtobe
appropriatelysavedastoenableyoutooutput.Thisisbeingtakencareof
intheprogram.
Thesourcecodeforcustomer,materialwisesalessummary:

REPORTYCL_CH06_ITAB14LINESIZE120LINECOUNT60
NOSTANDARDPAGEHEADING.
*********************************************************
*InternalTablesControlTotalsForTwoLevelSummary**
*********************************************************
************************************************************
*declaretablestructure.ensurethecontrolfields**
*areinthebeginningofstructure.theorderofthese**
*fieldsshouldbesameascontrolorderKUNNRMATNR**
*declaretable&othervariables**
***
*inputcompanycodePARAMETERS**
***
*loadinternaltablewithdatafromtheview.setup**
*LOOP...ENDLOOP.foreachrowconvertamountNETWR**
*totheoperatingcurrencyofcompanycode.makeKURRF**
*=0topreventoverflow.updateinthetableMODIFYetc.**
***
*sorttableonfieldsofcontrollevelsi.e.KUNNRMATNR**
***
*setupLOOP...ENDLOOP..setupcontrollevels**
*ATNEWKUNNR,ATENDOFMATNR,ATENDOFKUNNR,ATLAST**
*asperoutputformat.outputappropriateinfoineach**
*thesecontrollevelsasperoutputformat**
************************************************************
DATA:BEGINOFSALES_SUM_STRU,
KUNNRTYPEKNA1KUNNR,"Ilevelofcontrol
MATNRTYPEVBRPMATNR,"IIlevelofcontrol
NAME1TYPEKNA1NAME1,
MAKTXTYPEMAKTMAKTX,

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

40/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

NETWRTYPEVBRPNETWR,
KURRFTYPEVBRKKURRF,
ENDOFSALES_SUM_STRU,
SALES_SUM_TABLIKESTANDARDTABLEOFSALES_SUM_STRU,
NAME1TYPEKNA1NAME1,
MAKTXTYPEMAKTMAKTX,
STR(50)TYPEC,
BUTXTTYPET001BUTXT,
WAERSTYPET001WAERS.
**************************************************************
PARAMETERSCMP_CDTYPEVBRKBUKRSVALUECHECKDEFAULT3000.
TOPOFPAGE.
WRITE:/5TEXT001,CMP_CDNOGAP,'/'NOGAP,BUTXT,81(3)SYPAGNO.
WRITE:/46TEXT002,WAERS.
SKIP1.
WRITE:/5(79)SYULINE.
WRITE:/9TEXT003,29TEXT004,78TEXT005.
WRITE:/5(79)SYULINE.
**************************************************************
STARTOFSELECTION.
SELECTSINGLEBUTXTWAERSFROMT001INTO(BUTXT,WAERS)WHERE
BUKRS=CMP_CD.
SELECTKUNNRMATNRNAME1MAKTXNETWRKURRFFROM
YCL_CH06_CM_SALE
INTOTABLESALES_SUM_TABWHEREBUKRS=CMP_CD.
**convertamountNETWRtocompanycodecurrency
************************************************
LOOPATSALES_SUM_TABINTOSALES_SUM_STRU.
SALES_SUM_STRUNETWR=SALES_SUM_STRUNETWR*SALES_SUM_STRUKURRF.
SALES_SUM_STRUKURRF=0.
MODIFYSALES_SUM_TABFROMSALES_SUM_STRU.
ENDLOOP.
SORTSALES_SUM_TABBYKUNNRMATNR."sortinorderofcontrollevels
**looptogeneratecustomer,materialsummary
**********************************************
LOOPATSALES_SUM_TABINTOSALES_SUM_STRU.
NAME1=SALES_SUM_STRUNAME1.
ATNEWKUNNR."firstrowofnewvalueofKUNNRfetched
SKIP1.
FORMATINVERSEONCOLORCOL_POSITIVE.
CONCATENATESALES_SUM_STRUKUNNRNAME1INTOSTRSEPARATEDBY'/'.
WRITE:/5TEXT006,STR.
ENDAT.
MAKTX=SALES_SUM_STRUMAKTX.
ATENDOFMATNR."allrowsofparticularvalueofKUNNR&MATNRfetched
SUM.
FORMATINVERSEONCOLORCOL_GROUP.
WRITE:/8SALES_SUM_STRUMATNRUSINGNOEDITMASK,MAKTX,
(16)SALES_SUM_STRUNETWR.
ENDAT.
ATENDOFKUNNR."allrowsofparticularvalueofKUNNRfetched
SUM.
FORMATINVERSEONCOLORCOL_POSITIVE.
WRITE:/85(16)SALES_SUM_STRUNETWR.
ENDAT.
ATLAST."allrowsininternaltablefetched
SUM.
FORMATINVERSEONCOLORCOL_TOTAL.
WRITE:/102(16)SALES_SUM_STRUNETWR.
ENDAT.
ENDLOOP.

Thetextsymbols:

Figure635.ProgramYCL_CH06_ITAB14TextSymbols

Theoutputs:

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

41/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

Figure636.ProgramYCL_CH06_ITAB14Output

Figure637.ProgramYCL_CH06_ITAB14OutputwithGrand
Total

ANoteontheDataSourcesProgramYCL_CH06_ITAB14visvisthe
ProgramYCL_CH06_ITAB05
Considerthegrandtotalbeingoutputinthepresentprogramwiththe
grandtotalthatwasoutputinthepreviousprogram,
YCL_CH06_ITAB05,(customerwisesalessummary).Thegrandtotal
shouldbeidenticalinboththeseprograms.Thegrandtotalbeingoutput
inthesetwoprogramsarethetotalsalesforthecompanycodeinthe
currencyofthecompanycode.Thesourceofdatainthesetwoprograms
isdifferent.InthepresentprogramthefieldNETWRfromtableVBRPis
multipliedbytheexchangeratefieldKURRFandaccumulated.Inthe
previousprogramYCL_CH06_ITAB05,thefieldNETWRfromtable
VBRKismultipliedbytheexchangeratefieldKURRFandaccumulated.
Moreover,thedatainthesetwoprogramsisnotretrieveddirectlyfrom
thetablesbutfromdatabaseviewsinvolvingothertables.
Ifyouexecuteboththeprogramswithcompanycode=3000,thegrand
totalsareidentical.
Butifyouexecuteboththeprogramswithcompanycode=1000,thereis
amismatch.Thisisbecauseinthebillingdocument90023037,thesumof
individualvaluesinfieldNETWRoftableVBRPdonottallywiththe
valueinNETWRfieldoftableVBRK.AlsotheitemRNETINSTdoesnot
haveanEnglishdescription,soitgetsexcludedinyourdatabaseview.
Forcompanycode=0001,thereisnooutputwiththecurrentprogram
(nodataintheviewforcompanycode=001).Whereas,ifyouexecutethe
programYCL_CH06_ITAB05,thereisoutput.Thisisbecause,for
companycode=0001,allbillingdocumentitemshaveamaterial
number=ErsteHilfe.Thematerialnumber=ErsteHilfehasno
correspondingrowinthetablesMARAandMAKT(anorphanrow),soit
getsomittedinthedatabaseview.
TheseareproblemsrelatedtotheIDESserverdata.
Inyourdatabaseviews,youarenotinvolvingthesalesadministration
tableVBUK.ThebillingdocumentstablesVBRKandVBRParenot
directlylinked.Thesetwotablesarelinkedtoeachotherthroughthe
tablesalesadministrationVBUk.Inallthehandonexercisesinthe
book,youarelinkingthesetwotablesdirectlyforsimplicity.
Youarebeingmadeawareoftheissues.Inthepresentlearning
paradigm,youwillnotbotherwiththeseissues.
HandsOnExercise:InitializeInternalTablesRowsorComplete
Data
Youcaninitializeinternaltables,thatis,deletealltherowswithasingle
statement.Therearethreeseparatestatementsavailabletoclear
internaldata.Thethreestatementsare:
Clear
TheCLEARstatementcanclearanydataobject,thatis,elementary,
structured,orinternaltable.
WhentheCLEARstatementisusedonanelementarydataobject,the
elementarydataobjectisfilledwiththeINITIALvalue.TheINITIAL
valuefortypeCisspacesitisUnicode/ASCII/EBCDICzeroesfortypeD,
etc.RefertoChapter4forINITIALvaluesofdifferentpredefinedABAP
elementarytypes.
WhentheCLEARstatementisoperatedonastructureddataobject,each
oftheelementarydataobjectsorfieldsinthestructurearefilledwiththe
INITIALvaluesofthecorrespondingtype.
WhentheCLEARstatementisoperatedonaninternaltable,alltherows
intheinternaltablearedeleted.
IfaninternaltableexistswithaheaderlineandyouwanttheCLEAR
statementtooperateontheinternaltable,youshouldaddbrackets[].
WhenoperatingwiththeAPPENDstatement,itisagoodprogramming
practicetousetheCLEARstatementaftertheAPPENDstatementasto

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

42/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

ensuretheolddatathathasnotbeenoverwritteniscleared.
Refresh
TheREFRESHstatementisexclusivetointernaltables.Itdeletesall
rowsintheinternaltable.
Free
TheFREEstatementisexclusivetointernaltables.Itdeletesallrowsin
theinternaltableandreleasesthememoryaswell.
TheprogramYCL_CH06_ITAB15demonstratesthethreestatementsto
clearinternaltablesofdata.
Thesourceprogram:

REPORTYCL_CH06_ITAB15.
********************************************************
*InternalTables,RemoveDataCLEAR,REFRESH,FREE**
********************************************************
********************************************************
*declarethreeinternaltablesofstructureTCURT**
***
*loadthethreeinternaltableswithTCURTdata**
***
*operateDESCRIBETABLEonthethreeinternaltables**
*determinenumberofrows.outputthenumberofrows**
***
*operateCLEAR,REFRESH,FREEstatementsonthe**
*internaltables.**
***
*operateDESCRIBETABLEonthethreeinternaltables**
*determinenumberofrows.outputthenumberofrows**
********************************************************
DATA:CURR_TAB1TYPESTANDARDTABLEOFTCURTWITHHEADERLINE,
CURR_TAB2TYPESTANDARDTABLEOFTCURT,
CURR_TAB3TYPESTANDARDTABLEOFTCURTWITHHEADERLINE.
*****************************************************
STARTOFSELECTION.
SELECT*FROMTCURTINTOTABLE:CURR_TAB1,
CURR_TAB2,
CURR_TAB3.
*************************************************
DESCRIBETABLECURR_TAB1.
WRITE:/5'CURR_TAB1PRECLEARSTATUS:',(4)SYTFILL.
DESCRIBETABLECURR_TAB2.
WRITE:/5'CURR_TAB2PREREFRESHSTATUS:',(4)SYTFILL.
DESCRIBETABLECURR_TAB3.
WRITE:/5'CURR_TAB3PREFREESTATUS:',(4)SYTFILL.
SKIP2.
CLEARCURR_TAB1[]."todistinguishitabfromstructureof
"thesamename
DESCRIBETABLECURR_TAB1.
WRITE:/5'CURR_TAB1POSTCLEARSTATUS:',(4)SYTFILL.
REFRESHCURR_TAB2.
DESCRIBETABLECURR_TAB2.
WRITE:/5'CURR_TAB2POSTREFRESHSTATUS:',(4)SYTFILL.
FREECURR_TAB3.
DESCRIBETABLECURR_TAB3.
WRITE:/5'CURR_TAB3POSTFREESTATUS:',(4)SYTFILL.

Theoutputwilllooklikethis:

Figure638.ProgramYCL_CH06_ITAB15Output

MOVE,Assign,Copy,InternalTables
YoucanuseinternaltablesasoperandsintheMOVEandassignment
statements.WhenusingtheMOVEstatementormakingassignments,
ensurethatthesourceanddestinationinternaltableshaveidentical
structures.
Conclusion
Intheremainingchaptersofthisbook,internaltablesareinvariably
used.Forbetterperformance,thedefactowayofprocessingretrieved
datafromdatabasetablesorviewsisthroughtheinternaltables.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

43/44

1/5/2016

Chapter6:InternalTablesSAPABAP:HandsOnTestProjectswithBusinessScenarios

RefertotheEResourceprogramYCL_CH06_DATA_DEC_REFS.It
summarizesthedifferentreferencesusedtodeclaredatainABAP
programs.

PREV

Recommended
/ Queue
/ Recent(Classical
/ Topics /Reporting)
Tutorials / Settings / Blog / Feedback / Sign Out
Chapter 5: WRITE
Statement
2016 Safari.
Terms of Service / Privacy Policy

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch06.xhtml

NEXT

Chapter 7: Modularization

44/44

You might also like