Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
Recent
Topics
Tutorials
NEXT
PREV
Chapter 7: Modularization
CHAPTER8
Highlights
Chapter 9: SELECTION-SCREENS
Settings
Feedback
OpenSQLDataRetrieval
Sign Out
Introduction
SAPOpenSQListhedefactoSQLusedtooperatedatabasetablesin
ABAPprograms.ItwasintroducedinChapter5onapreviewbasis.In
Chapter5,youwantedsubstantialoutputrunningintomultiplepages.
Youresortedtoretrievinglargeamountsofdataavailableinadatabase
tablethatcouldproducemultiplepageoutput.YouusedOpenSQLto
Settings
10 days left in your trial. Subscribe.
Feedback
retrievethedata.YoualsousedOpenSQLdataretrievalinChapter6to
loadinternaltables.
Sign Out
YouhavebeenexposedtosomebasicformsoftheSELECTstatementin
thesechapters.SimilartootherSQLofferings,theSELECTstatementis
usedinOpenSQLtoretrievedatafromdatabasetablesandviews.You
canusetheSQLofaspecificdatabaseaswell.CalledNativeSQLinSAP
documentationterminology,itrestrictsyoutorunningtheprogramonly
onSAPsystemswiththatspecificdatabaseinstalled.Inthischapter,you
arelearningonlytheSELECTstatement(dataretrieval)withits
variants.Theotherdatamanipulationstatements:INSERT,UPDATE,
MODIFY,DELETE,etc.,arecoveredinChapter14.
Figure81representstheprocessingofOpenSQLvisvisNativeSQL
statementsbytheABAPinterpreterandABAPruntimedatabase
Enjoy Safari? Subscribe Today
interfacesystem.
Figure81.OpenSQL,NativeSQLDataManipulationFlow
LettheprocessingofOpenSQLstatementsbytheABAPruntime
databaseinterfacesystembetraced.FromtheABAPinterpreter,the
OpenSQLstatementisprocessedfirstbythedatabaseinterface.Itis
determinedwhetherthetabledefinitionexistsintheDDIC.Ifatable
definitionexistsintheDDIC,theOpenSQLstatementsaretranslatedto
theSQLstatementsoftheinstalleddatabase.Otherinformationis
extractedfromtheDDICtabledefinitionsuchastablemaintenance,
technicalsettings,domainanddataelementinformation,etc.TheOpen
SQLtranslatedstatementsarepassedtothedatabasemetadata.Andthen
thedatabasemetadatatakesover.
AftertheOpenSQLoperationonthedatabase,processingisviathe
databaseinterface(fillingbuffers,etc.)andbacktotheABAPinterpreter.
AselaborateduponinChapter1,undertheheadingClientCode
Perspectives,theOpenSQLbydefaultfiltersandoperatesonlyonrow/s
belongingtotheclientcodeintowhichtheuserisloggedinforclient
dependenttables.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
1/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
InNativeSQL,theSQLstatementsarepasseddirectlyfromtheABAP
interpretertotheinstalleddatabasesmetadataandaftertheoperation
onthedatabase,backtotheABAPinterpreter.Thereisabsolutelyno
referencetotheDDIC.
Inthischapter,youwillgothroughthedifferentvariationsoftheOpen
SQLSELECTstatement.Thevariationsarethese:the<result>
specification,<source>specification,<destination>specification,
WHERE<condition>specification,andtheORDERBY<sort>
specification.
TheOpenSQLspecialfeaturesofruntimespecificationsof<result>,
<source>,<destination>,WHERE<condition>,andORDERBY<sort>
areintroduced.
ThechapteralsocoverstheABAPFIELDSYMBOLS.Somerudimentary
applicationsoftheFIELDSYMBOLSaredemonstrated.TheFIELD
SYMBOLSareusedtoaccessandprocessrowsofaninternaltable
directlyinsteadoffetchingthemintoastructureandprocessing.The
creationofruntimeordynamicdataobjects(OOPS)isintroduced.
FIELDSYMBOLSarethenusedtoaccessindividualfieldsofaruntime
createdstructuredobject.
OpenSQLSELECTStatement
Insteadofintroducingyoutoasinglecomprehensivesyntaxofthe
SELECTstatement,itisbeingintroducedinpiecesasdifferentfeatures
andvariants.Afterchaptercompletion,youcannavigatetotheonline
SAPdocumentationoftheSELECTstatement(pressF1onthekeyword
SELECT),andyouwillbeabletorelatetothesinglecomprehensive
syntaxoftheSELECTstatementwithitsmyriadoptions.
SELECTENDSELECTwithWHERECondition,ORDERBYandUPTO
Clauses
ThemostbasicformoftheSELECTstatementistheSELECT
ENDSELECTstatement,whereonerowisfetchedfromthedatabase
tableintoadestinationstructureordestinationofindividualfields:
SELECT<result>FROM<source>
INTO[CORRESPONDINGFIELDSOF]<destination>
[WHERE<condition>]
[ORDERBY<sortspecification>]
[UPTO<noofrows>ROWS].
.
ENDSELECT.
<result>:Thiscanbe*orindividualfields.(*shouldbeused
judiciously).
<source>:Thiscanbeadatabasetableordatabasevieworprojection
view.
<destination>:Thiscanbeastructureorlistofindividualfields.The
individualfieldshavetobeenclosedinparenthesesseparatedby
commas,like:(KUNNR,NAME1,ORT01).Forasinglefieldasdestination,
theparenthesescanbeomitted.
CORRESPONDINGFIELDSOF:Theadditionofthisphraseapplies
whenthedestinationisastructureandwhenthesourceanddestination
arenotidenticalintermsofthenumberoffieldsand/ortheirorder.The
datamovementtakesplacefieldbyfieldwiththeCORRESPONDING
FIELDSOFusage.
<condition>:Aconditioncanbesimpleorcompound.Inacompound
condition,thesimpleconditionsareconjoinedbythelogicaloperators
ANDandOR.ThelogicaloperatorNOTistobeusedjudiciouslyfor
performancereasons.
Thefollowingconditionoperatorsaresupported:
Table81.ConditionOperatorsinOpenSQL
Operator
Description
EQ/=
EqualTo
NE/<>/><
NotEqualTo
GT/>
GreaterThan
GE/>=
GreaterThanOrEqualTo
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
2/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
LT/<
LessThan
LE/<=
LessThanOrEqualTo
BETWEEN
BetweenTwoValues(interval)
IN
InaSetOfValues
LIKE(%,_)
StringPatternComparison
<sortspecification>:Youcangetdatasortedbyfieldsin
ascending/descendingorderlike:ORDERBYORT01ASCENDING
NAME1DESCENDING.
IfyoudonotspecifytheadditionASCENDING/DESCENDING,the
defaultisASCENDING.
<noofrows>:Theloopwillrun<noofrows>timesoritwillfetchonly
<noofrows>rows.Thisvariationisusedatthetestingstage.
TheSELECTstatementcanalsobenestedbutisnotadvisable.Youcan
useonelevelloopconstructSELECTENDSELECTjudiciously.Youused
ittobuildasummaryinternaltablewiththeCOLLECTstatement.Ifthe
dataissmall,youcanuseit.Inaclientserverenvironment,the
suggestedprocedureistoloadaninternaltablefromthedatabasetable
andsetuprowbyrowprocessingwiththeinternaltablelooping
construct.
ThesystemfieldSYDBCNTissettothenumberofrowsfetchedorthe
passnumberoftheSELECTENDSELECTloop.ThesystemfieldSY
SUBRCissettozeroifarowisfetchedandissettononzero,ifarow
cannotbefetched.
SELECTSINGLEwith/withoutWHEREcondition
Toretrieveasinglerowfromadatabasetableordatabaseviewor
projectionview,youuse:
SELECTSINGLE<result>
FROM<source>
INTO[CORRESPONDINGFIELDSOF]<destination>
[WHERE<condition>].
ThisisnotaloopingconstructnoENDSELECT.Themeaningof
<result>,<source>,<destination>,etc.,arethesameasexplainedinthe
precedingsyntax.Thestatementwillfetchthefirstrowinthetableor
viewfulfillingtheWHEREconditionifthereisaWHEREcondition,else
itfetchesthefirstrow.
ThoughtheWHEREconditionisoptional,inpracticaltermsitcouldbe
mandatory.
Ifarowisfetched,thesystemfieldSYSUBRCissettozeroorelsetonon
zero.ThesystemfieldSYDBCNTissetto1ifSYSUBRC=0.
SELECTINTOTABLE
Tofetchdatafromadatabasetableordatabasevieworprojectionview
intoaninternaltable,youusethefollowingsyntax:
SELECT<result>FROM<source>
INTO[CORRESPONDINGFIELDSOF]TABLE<itab>
[WHERE<condition>]
[ORDERBY<sortspecification>]
[UPTO<noofrows>ROWS].
<itab>isthespecificationfortheinternaltableotherclauseshavethe
samemeaningasinearliersyntaxes.ThereisnoENDSELECT
statementthereisnorepetitive,loopingprocess,anddataisfetchedinto
theinternaltableatonego.Thisisthepreferredwayofdataretrievalin
theclientserverenvironment.
ThesystemfieldSYDBCNTissettothenumberofrowsfetched.The
systemfieldSYSUBRCissettozeroifarow/rowsisfetched,orelseitis
settononzero.
HandsOnExerciseINTOTABLEPACKAGESIZE
Ifthenumberofrowsbeingfetchedintoaninternaltableisveryhigh,
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
3/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
thereisapressureontheapplicationserverofRAMusage.Then,instead
ofloadingtheinternaltablefully,itcanbeloadedpartiallyinbatchesof
aspecifiednumberofrows.Thefetchedrowsareprocessedandthenext
batchofrowsfetchedintotheinternaltablereplacingthepreceding
batch.Thisprocessoffetchingandprocessinggoesonuntilallrowsare
processed.ThisisaloopingprocessandhencetheENDSELECT
statement.Thesyntax:
SELECT<result>FROM<source>
INTO[CORRESPONDINGFIELDSOF]TABLE<itab>
PACKAGESIZE<noofrowsinbatch>[WHERE<condition>]
[ORDERBY<sortspecification>]
[UPTO<noofrows>ROWS].
ENDSELECT.
PACKAGESIZEisthekeyphrasetoprovidethebatchsizeinnumberof
rows.
<noofrowsinbatch>canbeliteralorvariabletospecifythenumberof
rowsinthebatch.
Otherclausescarrythesamemeaningasintheearliersyntaxes.
Asahandsontofetch,processdatawiththissyntax,yououtputcustomer
list,fetchingthedatainbatches,batchsize,orpackagesizeinputthrough
thePARAMETERSstatement.Thesourceprogram:
REPORTYCL_CH08_02_PSIZE_INTO_TABNOSTANDARDPAGEHEADING
LINESIZE95LINECOUNT60.
*********************************************************
*FetchDataFromDatabaseTableInBatchesINTOTABLE**
*********************************************************
******************************************************
*ifnoofrows/dataisverylargeexertingpressure**
*onRAMusage,theninthisscenariodatacanbe**
*fetchedinbatchesofsmallersize.**
***
*inthepresentscenario,youarefetchingdatain**
*batchesof1000rowsatatime.thisbatchsize**
*canbespecifiedwiththephrasePACKAGESIZE&a**
*literal/variable.**
***
*everytimebatchofrowsisfetched,existingdata**
*intheinternaltableisoverwritten/deleted.**
***
*atanyinstantonlyonebatchofdata/rowsis**
*existingintheinternaltable.**
***
*youareusinganINCLUDEprogram**
*YCL_CH08_01_INCLUDE_HEADINGfornonstandard**
*header.youareusingthissameINCLUDEprogram**
*forthehandsonYCL_CH08_03_PSIZE_APPEND_TAB**
******************************************************
******************************************************
*declaredata.inputPACKAGESIZEthruPARAMETERS**
*INCLUDEprogramforheading**
***
*retrieveabatchofrowswithSELECT...PACKAGE**
*SIZE...etc.**
*outputretrievedbatchLOOPAT...WRITE...ENDLOOP**
*ENDSELECT.**
******************************************************
DATA:CUSTOMER_TABTYPESTANDARDTABLEOFYCL_CH05_CUST_STRU
WITHHEADERLINE,
CNTR(3)TYPEPDECIMALS0,
CDATETYPESTRING.
PARAMETERS:PKSZ(4)TYPENDEFAULT1000.
********************************************
INCLUDEYCL_CH08_01_INCLUDE_HEADING."INCLUDEprogramforheading
STARTOFSELECTION.
CONCATENATESYDATUM+6(2)SYDATUM+4(2)SYDATUM+0(4)
INTOCDATESEPARATEDBY'/'.
*************************************************
SELECTKUNNRNAME1STRASORT01PSTLZFROMKNA1INTO
TABLECUSTOMER_TABPACKAGESIZEPKSZ.
LOOPATCUSTOMER_TAB."outputfetchedbatch
CNTR=CNTR+1."cannotuseSYTABIXforserialnumber
WRITE:/5(5)CNTR,CUSTOMER_TABKUNNRUSINGNOEDITMASK,
CUSTOMER_TABNAME1,CUSTOMER_TABORT01.
ENDLOOP.
SKIP2."gapbetweenbatchesofdata
ENDSELECT.
YouareusingINCLUDEprogram
YCL_CH08_01_INCLUDE_HEADINGtooutputtheheadingforthe
customerlist.YouarealsousingthissameINCLUDEprogramtooutput
theheaderforthenexthandsonexercise:
YCL_CH08_03_PSIZE_APPEND_TAB.
ThisINCLUDEprogramcontainstheTOPOFPAGEeventalongwith
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
4/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
theothercodelinestooutputtheheader.Noticethepositionofthe
INCLUDEstatementintheprogram
YCL_CH08_03_PSIZE_INTO_TAB.Reusabilitythatis,
modularizationtechniques,hasbeenemployed.
ThesourcelinesofINCLUDEprogram
YCL_CH08_01_INCLUDE_HEADING:
****************************************************
*INCLUDEprogramforheadingofcustomerlist**
*usedbyprograms:YCL_CH08_02..**
*YCL_CH08_03..**
****************************************************
TOPOFPAGE.
WRITE:/5TEXT001,CDATE,92(3)SYPAGNO.
WRITE:/5(89)SYULINE.
WRITE:/5TEXT002,11TEXT003,22TEXT004,58TEXT005.
WRITE:/6TEXT006,13TEXT007.
WRITE:/5(89)SYULINE.
******************************************************************
AscreenshotofthetextsymbolsisshowninFigure82.
Figure82.Program:YCL_CH08_02_PSIZE_INTO_TABText
Symbol
TheoutputwillbelikeFigure83.
Figure83.Program:YCL_CH08_02_PSIZE_INTO_TAB
Output
HandsOnExerciseAPPENDINGTABLEPACKAGESIZE
Ifthenumberofrowsbeingfetchedintoaninternaltableisveryhigh
andcloggingthenetworkanddatabaseserverandtherenoapplication
serverRAMissues,then,insteadofloadingtheinternaltablefullyat
onego,itcanbeloadedinincrementsofbatchesofaspecifiednumberof
rows.Whentheinternaltablehasbeenfullyloaded,itcanbeprocessed.
Theprocessofloadingtheinternaltablewithanincrementalnumberof
rowsisagainaloopingprocessandhencetheENDSELECTstatement.
Thesyntax:
SELECT<result>FROM<source>
APPENDING[CORRESPONDINGFIELDSOF]TABLE<itab>
PACKAGESIZE<noofrowsinbatch>
[WHERE<condition>]
[ORDERBY<sortspecification>]
[UPTO<noofrows>ROWS].
ENDSELECT.
Theonlydifferencebetweentheprecedingsyntaxandthecurrentone
arethekeywords:INTOandAPPENDING.Theprecedingsyntaxwas
usingINTOTABLE.
WhenthekeywordINTOisusedasintheprecedingexample,datawas
fetchedinbatchesofaspecifiednumberofrows,andthecurrentbatch
wipedordeletedtheexistingdataintheinternaltable.
WhenthekeywordAPPENDINGisused,dataisfetchedinbatchesofa
specifiednumberofrows,andthecurrentbatchisappendedtothe
alreadyexistingdataintheinternaltableinthecaseofastandardtable.
Incaseofsortedandhashedtables,thecurrentbatchofrowsinserttothe
existingdataintheinternaltable.
Inallothersituations,clausesremainthesameforthetwosyntaxes.
Asahandsonexerciseusingthissyntaxtofetchinbatchesandbuildthe
internaltable,thenprocesstheinternaltable,yououtputagainthe
customerlist,batchsize,orpackagesizeinputthroughthePARAMETERS
statement.Thesourceprogram:
REPORTYCL_CH08_03_PSIZE_APPEND_TABNOSTANDARDPAGEHEADING
LINESIZE95LINECOUNT60.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
5/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
**************************************************************
*FetchDataFromDatabaseTableInBatchesAPPENDINGTABLE**
**************************************************************
******************************************************************
*ifnoofrows/dataisverylargeputtingpressureonnetwork,**
*theninthisscenariodatacanbefetchedinbatchesof**
*smallersize&appendedtotheinternaltable.inthepresent**
*scenario,youarefetchingdatainbatchesof1000rowsata**
*time.thisbatchsizecanbespecifiedwiththephrasePACKAGE**
*SIZE&aliteral/variable.everytimebatchofrowsis**
*fetched,existingdataintheinternaltableisappendedto.**
*attheendofSELECT...ENDSELECTloop,internaltable**
*containsallthefetchedrowsofallthebatches.**
******************************************************************
******************************************************
*declaredata.inputPACKAGESIZEthruPARAMETERS**
*INCLUDEprogramforheading**
***
*retrieveabatchofrowswithSELECT...PACKAGE**
*SIZE...etc.appendtoexistingdataENDSELECT.**
***
*outputretrievedbatchLOOPAT...WRITE...ENDLOOP**
******************************************************
DATA:CUSTOMER_TABTYPESTANDARDTABLEOFYCL_CH05_CUST_STRU
WITHHEADERLINE,
CNTR(3)TYPEPDECIMALS0,
CDATETYPESTRING.
PARAMETERS:PKSZ(4)TYPENDEFAULT1000.
********************************************
INCLUDEYCL_CH08_01_INCLUDE_HEADING."heading
STARTOFSELECTION.
CONCATENATESYDATUM+6(2)SYDATUM+4(2)SYDATUM+0(4)
INTOCDATESEPARATEDBY'/'.
SELECTKUNNRNAME1STRASORT01PSTLZFROMKNA1APPENDING
TABLECUSTOMER_TABPACKAGESIZEPKSZ.
ENDSELECT.
*********************************************************
LOOPATCUSTOMER_TAB.
WRITE:/5(5)SYTABIX,CUSTOMER_TABKUNNRUSINGNOEDITMASK,
CUSTOMER_TABNAME1,CUSTOMER_TABORT01.
CNTR=SYTABIXMODPKSZ.
IFCNTR=0.
SKIP2."gapbetweenbatches
ENDIF.
ENDLOOP.
TheoutputshouldlooklikeFigure84.
Figure84.Program:YCL_CH08_03_PSIZE_APPEND_TAB
Output
HandsOnExerciseSELECTDISTINCT
Toretrievedistinctoruniquevaluesforfield/s,youusetheOpenSQL
SELECTDISTINCTstatement.
Thesyntax:
SELECTDISTINCT<result>FROM<source>
{INTO|APPENDING}[CORRESPONDINGFIELDSOF]<destination>
[PACKAGESIZE<noofrowsinbatch>]
[WHERE<wherecondition>]
[ORDERBY<sortspecification>]
[UPTO<noofrows>ROWS].
[ENDSELECT].
ApartfromDISTINCT,alltheotherclauseshavebeenexplainedand
havethesamemeaningasinearliersyntaxes.TheENDSELECThas
beenindicatedasoptional,dependingonthe<destination>.Ifthe
<destination>isastructureorindividualfields,itwillbealooping
constructwithENDSELECT.Ifthedestinationisaninternaltableand
PACKAGESIZEisused,againitwillbealoopingconstructwith
ENDSELECT.Ifthedestinationisaninternaltablewithouttheaddition
ofPACKAGESIZE,thenitiscaseofretrievingdataatonego,andthere
willbenoENDSELECT.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
6/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
Asahandsonexercise,youarerepeatingtheChapter6internaltable
handsonexercise:YCL_CH06_ITAB10.Thishandsonexerciselisted
outthecustomerswithbillingdocumentsofagivencompanycode.Your
basicsourceofdatawasthetableVBRK,andthereweretwoissuesyou
facedthen:thetableVBRKcouldcontainmultipleentriesforacustomer,
andthetableVBRKdoesnotcontainthecustomernameandcitythatyou
wantedintheoutput.Youaddressedtheseissuesbycreatingadatabase
viewwithtablesVBRKandKNA1(toincorporatethecustomernameand
city)loadinganinternaltablewithdatafromthisviewandusingthe
internaltablestatementDELETEADJACENTDUPLICATES.Before
issuingtheDELETEADJACENTDUPLICATESstatement,theinternal
tablewassortedinascendingorderofthefieldKUNNR.(Internaltable
hastobesortedinascendingorderofthefieldsforwhichduplicatesareto
beeliminated.)Thisstatementdeletedmultipleentriesintheinternal
tableforavalueoffieldKUNNR,reducingthemtoonerowforevery
valueofKUNNR.
Forthecurrenthandsonexercise,youareusingthesamedatabaseview
ofChapter6.YouareusingtheSELECTDISTINCTstatementtofetch
distinctvaluesoffieldsKUNNR,NAME1,andORT01.
CopythetextsymbolsfromprogramYCL_CH06_ITAB10(transaction
codeSE32,etc.)tooutputtheheader.
Thesourceprogram:
REPORTYCL_CH08_04_SELECT_DISTINCTLINESIZE95LINECOUNT60
NOSTANDARDPAGEHEADING.
********************************************
*SELECTDISTINCTListBilledCustomers**
*ofaSpecifiedCompanyCode**
********************************************
********************************************************
*ifrowswithunique/distinctfieldvaluesaretobe**
*fetched,thenyoucanusetheSELECTDISTINCTSQL**
*statementvariation.**
***
*inthishandson,youhavegeneratedthesameoutput**
*asinprogramYCL_CH06_ITAB10:listofcustomers**
*withbillingdocuments.**
***
*acustomermayhavemultiplebillingdocuments.**
*youwereusingtheinternaltablestatement**
*DELETEADJACENTDUPLICATES...toreducemultiple**
*occurrencesofacustomercodevalueKUNNRtoa**
*singleoccurrence.yoursourcedatawasadatabase**
*viewwithtablesKNA1&VBRK.**
***
*youareusingthesameview,usingaSELECTDISTINCT**
*statementtogenerateacustomerlistwithbilling**
*documents.**
********************************************************
********************************************************
*declaredata.inputcompanycode.retrievecompany**
*codename.(SELECTSINGLEetc.)forheading**
***
*useSELECTDISTINCT...toretrievedatafromview**
*intointernaltable.sortinternaltable.output**
*frominternaltable:LOOPAT...ENDLOOP.**
********************************************************
TYPES:BEGINOFCUSTOMERS_STRU_TYPE,
KUNNRTYPEKNA1KUNNR,
NAME1TYPEKNA1NAME1,
ORT01TYPEKNA1ORT01,
ENDOFCUSTOMERS_STRU_TYPE.
DATA:CUSTOMERS_TABTYPESTANDARDTABLEOFCUSTOMERS_STRU_TYPE,
CUSTOMERS_STRUTYPECUSTOMERS_STRU_TYPE,
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.
SELECTDISTINCTKUNNRNAME1ORT01FROMYCL_CH05_VBRKKNA
INTOTABLECUSTOMERS_TAB
WHEREBUKRS=CCODE.
SORTCUSTOMERS_TABBYKUNNR.
LOOPATCUSTOMERS_TABINTOCUSTOMERS_STRU.
WRITE:/5(4)SYTABIX,CUSTOMERS_STRUKUNNRUSINGNOEDITMASK,
CUSTOMERS_STRUNAME1,CUSTOMERS_STRUORT01.
ENDLOOP.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
7/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
TheoutputwillappearlikeFigure85.
Figure85.Program:YCL_CH08_04_SELECT_DISTINCT
Output
HandsOnExerciseAggregateFunctions
Onelevelsummarizeddatacanbeproducedbyusingaggregate
functionsoftheOpenSQLSELECTstatement.
TheOpenSQLaggregatefunctionsdonotsupportexpressions.You
cannotwriteSUM(NETWR*KURRF)thatis,thesumoftheamountin
documentcurrencymultipliedbytheexchangerate).Practically
speaking,theOpenSQLaggregatefeaturecannotbeusedforamount
summarizations.Alternatively,youcanwritetoanintermediate
databasetable,fortheresultofamountmultipliedbytheexchangerate
andusethisintermediatetableinanOpenSQLstatementwith
aggregatefunctionsforamountfieldslikeNETWR.
Theaggregatefunctions,though,canbeusedforquantityfields.Youare
assuredthatmaterialsaresoldinonespecificunitofmeasurefora
materialcodeandpurchasedinanotherspecificunitofmeasurefora
materialcodeforaplant.
Thesyntax:
SELECT<groupbyfields><aggregatefunction>([DISTINCT]<field>)as<alias1><aggregatefunction>([DISTINCT]<field>)as<alias2>.
{INTO|APPENDING}<destination>[UPTO<noofrows.]
[WHERE<wherecondition>]
GROUPBY<groupbyfields>
[HAVING<havingcondition>]
[ORDERBY<sortspecification>].
[ENDSELECT].
<groupbyfields>:Thesummarizingfields.
<aggregatefunction>:TheOpenSQLsupportsthefollowingaggregate
functions:
SUM
Totalforthe<field>.Thisshouldbeanumericfield.Ifthekeyword
DISTINCTisusedintheargumentoftheaggregatefunction,only
distinctvaluesareconsideredforaggregateoperation.
COUNT
Numberofrowsforthe<field>.COUNT(*)returnsnumberofrowsfor
theselection.COUNT(DISTINCT<field>)willreturnthenumberof
rowsforDISTINCTvaluesof<field>.
MAX
Maximumvalueforthe<field>.IfthekeywordDISTINCTisusedinthe
argumentoftheaggregatefunction,onlydistinctvaluesareconsidered
foraggregateoperation.
MIN
Minimumvalueforthe<field>.IfthekeywordDISTINCTisusedinthe
argumentoftheaggregatefunction,onlydistinctvaluesareconsidered
foraggregateoperation.
AVG
Averageforthe<field>.Thisshouldbeanumericfield.Ifthekeyword
DISTINCTisusedintheargumentoftheaggregatefunction,andonly
distinctvaluesareconsideredforaggregateoperation.
<alias1>:Theaggregatevaluesreturnedhavetobeloadedintoa
structureortableorindividualfields.(INTO/APPENDING
<destination>.)Throughthe<alias1>,<alias2>..,youareassigning
namestothereturnedaggregatevaluestoenablethemtobeloadedinto
thedestination.
<havingcondition>:Theconditionsoperatingonaggregatefunctions.
Theotherclausescarrythesamemeaningasinearliersyntaxes.The
ENDSELECThasbeenindicatedasoptionalandwilldependonthe
<destination>andpresence/absenceoftheclausePACKAGESIZE.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
8/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
Thecurrenthandonexerciseisasummarizationofmaterialwise
quantitiessold.YourbasicSourceofdataisthetableVBRP(Billing
DocumentItems).Formaterialdescriptions,youneedtoaccesstable
MAKT.SoyouareusingtheviewYCL_CH08_VBRP_MKcreatedwith
thetablesVBRPandMAKT.Theoutputlayout:
Table82.Program:YCL_CH08_05_AGGREGATE_FUNC
OutputLayout
Field
Description
Column
Positions
SYDBCNT
SerialNumber
005008(4)
MATNR
MaterialCode
010027(18)
MAKTX
MaterialDescription
029068(40)
VRKME
UnitofMeasure
070072(3)
COUNT(*)
CountofSales
074078(5)
SUM(
SumofQuantitySold
080091(12)
MAX(
MaximumofQuantity
093104(12)
FKIMG)
Sold
MIN(
MinimumofQuantity
FKIMG)
Sold
FKIMG)
106117(12)
ThedatabaseviewYCL_CH08_VBRP_MKwillappearlikeFigures86
to88.
Figure86.DatabaseView:YCL_CH08_VBRP_MKTablesand
JoinConditions
Figure87.DatabaseView:YCL_CH08_VBRP_MKViewFields
Figure88.DatabaseView:YCL_CH08_VBRP_MKSelection
Conditions
Thesourceprogram:
REPORTYCL_CH08_05_AGGREGATE_FUNCNOSTANDARDPAGEHEADING
LINESIZE120LINECOUNT60.
**********************************************
*SELECTStatementwithAggregateFunctions**
**********************************************
**************************************************************
*SELECTstatementaggregatefunctionstogetsummarized**
*data.**
***
*aclarification:theopensqlaggregtefunctionsdo**
*notsupportexpressions.youcannotwrite**
*SUM(NETWR*KURRF)i.e.sumof**
*(amountindocumentcurrencymultipliedbyexchangerate)**
***
*practicallyspeaking,theopensqlaggregatefeature**
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
9/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
*cannotbeusedforamountsummarization.unlessyouwrite**
*toanintermediatedatabasetabletheresultofamount**
*multipliedbytheexchangerateandusethisintermediate**
*tableinopensqlstatementwithaggregatefunctionsfor**
*amountfieldslikeNETWR.**
***
*theaggregatefunctionsthoughcanbeusedforquantity**
*fields.becauseyouareassuredthatquantitiesaremostly**
*soldinonespecificunitofmeasureforamaterialcode,**
*purchasedinanotherspecificunitofmeasurefora**
*materialcode.(ofspecificorganizationalunit)**
***
*thecurrenthandon,issummarizationofmaterialwise**
*quantitiessold**
*yourbasicSourceofdataisthetableVBRP.formaterial**
*description,youneedtoaccesstableMAKT.soyouare**
*usimgtheviewYCL_CH08_VBRP_MKcreatedwiththetables**
*VBRP,MAKT.**
**************************************************************
**************************************************************
*declaredata.codeforheading.**
*useSELECTstatementwithaggregatefunctionsSUM(),**
*MAX(),MIN(),COUNT(*)toretrieveandstorefora**
*materialcodetotalquantitysold,maximumquantitysold**
*atatime,minimumsoldatatime,numberoftimessold.**
*outputtheretrieveddata.ENDSELECT.**
**************************************************************
DATA:BEGINOFSALES_STRU,
MATNRTYPEMATNR,
MAKTXTYPEMAKTX,
VRKMETYPEVRKME,
CONTTYPEI,
TOTALTYPEFKIMG,
MAXTYPEFKIMG,
MINTYPEFKIMG,
ENDOFSALES_STRU.
*******************************************
TOPOFPAGE.
WRITE:/5TEXT001,115(3)SYPAGNO.
SKIP1.
WRITE:/5(112)SYULINE.
WRITE:/5TEXT002,10TEXT003,30TEXT004,
70TEXT005,74TEXT006,82TEXT007,
96TEXT008,109TEXT009.
WRITE:/6TEXT010.
WRITE:/5(112)SYULINE.
*******************************************
STARTOFSELECTION.
SELECTMATNRMAKTXVRKMECOUNT(*)ASCONTSUM(FKIMG)ASTOTAL
MAX(FKIMG)ASMAXMIN(FKIMG)ASMINFROMYCL_CH08_VBRP_MK
INTOSALES_STRU
GROUPBYMATNRMAKTXVRKMEHAVINGSUM(FKIMG)<>0
ORDERBYMATNR.
WRITE:/5(4)SYDBCNT,SALES_STRUMATNRUSINGNOEDITMASK,
SALES_STRUMAKTX,SALES_STRUVRKME,(5)SALES_STRUCONT,
(12)SALES_STRUTOTAL,(12)SALES_STRUMAX,(12)SALES_STRUMIN.
ENDSELECT.
TheoutputwillbelikeFigure89.
Figure89.Program:YCL_CH08_05_AGGREGATE_FUNC
Output
Inthisprogram,youhaveassignedtheaggregatesaliases(AS)andthe
OpenSQLdestinationisastructure.Youwantedtheunitofmeasurefield
VRKMEintheoutput.SoyouhadtoincludeitperforceintheGROUPBY
fields.
Yououtputthislistforaspecifiedcompanycode.Youwillbeproducing
thiskindoflistsplantwise(i.e.,fieldWERKS).Aplantwithinacompany
codewillbeproducingspecifiedproductsorproductlines.Youare
notproducingareportforaspecifiedplant.Inthetrainingparadigm,
youcanbeabsolvedofthis.
IntheEResource,therearetwomorevariationsofthisprogramusing
aggregatefunctionsofSELECTstatement.Theyare:
YCL_CH08_06_AGGREGATE_FUNC_VR1
YCL_CH08_07_AGGREGATE_FUNC_VR2
InthefirstprogramYCL_CH08_06_AGGREGATE_FUNC_VR1,the
destinationinSELECTstatementisspecifiedasindividualfields.No
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
10/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
aliasesarerequired,andsonoaliasesareassigned.
InthesecondprogramYCL_CH08_07_AGGREGATE_FUNC_VR2,the
destinationinSELECTstatementisspecifiedasaninternaltablewitha
PACKAGESIZEaddition,justtodemonstratethattheadditionPACKAGE
SIZEcanbeusedinanaggregatefunctionSELECTstatement.Noaliases
arerequired,andsonoaliasesareassigned.
Allthethreeprograms:
YCL_CH08_05_AGGREGATE_FUNC
YCL_CH08_06_AGGREGATE_FUNC_VR1
YCL_CH08_07_AGGREGATE_FUNC_VR2
Producethesameoutput.
SELECTStatementUsingMoreThanOneTableorViewJoins
YouhaveusedasingledatabasetableordatabaseviewintheSELECT
statementsuntilnow.YoucancodeSELECTstatementusingmorethan
onetableorcanviewitbyemployingtheinnerandleftouterjoin.
TheDDICdatabaseviewsimplementinnerjoin.Soinsteadofwritingan
OpenSQLstatementimplementinginnerjoin,abetteroptionisto
createaDDICdatabaseviewwiththereusabilityadvantageand
avoidanceofcoding.Thisistrueifyouwantonlydatabasetablesto
participateintheinnerjoin.Butifyouwantdatabaseviewsand
projectionviewstoparticipateintheinnerjoin,youhavetowritea
SELECTstatementforinnerjoin.IntheDDICdatabaseandprojection
views,thesourceofdatacanonlybetables.Syntax:thesyntaxforjoins
givenbelowisonlyforthejoinpartoftheSELECTstatement.Other
clausessuchasdestinationandtheWHEREcondition,etc.,areimplicit.
Thesyntaxforinnerandleftouterjoins:
<sourceleft>[AS<aliasleft>]
{[INNER]JOIN}|{LEFT[OUTER]JOIN}
{<sourceright>[AS<aliasright>]ON<joincondition}
INNERJOIN,JOINissynonymous.
LEFTOUTERJOIN,LEFTJOINissynonymous.
Sinceyouarefetchingandcomparingfieldsfrommultiplesources,
(tablesandviews),thefieldshavetobereferredwithsourcequalification
intheSELECTstatement.YouwillrefertofieldKUNNRas
KNA1~KUNNR.Youusethetildecharacter(~)toassociateafieldwithits
originorsourcejustlikeyouwereusingthehyphen/dash()characterto
associateafieldwithastructure.
Youcanassignaliasestothesource(tablesandviews).Youshouldthen
refertothesourcesbyaliasesonly.
JoinOperation:Firstly,arecapitulationofinnerjoinandabare
definitionofleftouterjoinareinplace.
Lettherebeasimplescenariowiththeveryfamiliartables.Letthe
SELECTinnerandouterjoinsbeimplementedwithfieldsfromtables
KNA1andVBRK(customerprimaryandbillingdocumentheader).The
twotablesarejoinedthroughforeignkeyrelationshipfields:MANDT,
KUNNRfromKNA1andMANDT,andKUNAGfromVBRK.
Ifyouhaveinnerjoinofthesetables,arowmustexistinboththetables
forittoappearintheresult.Ifyouassumethatthereisnobilling
documentwithoutavalidcustomercode(noorphanrows),alltherows
fromthetableVBRKwillappearintheresult.Orallthecustomershaving
billingdocumentswillappearintheresult,andacustomerhaving
multiplebillingdocumentswillhavethatmanyrowsintheresult.But
customershavingnobillingdocumentswillnotappearintheresult.
Whenyouhaveleftouterjoinofthesetables,withtheprimarytable
KNA1ontheleftsideofthejoin,arowexistingineitherofthetableswill
appearintheresult.Ifyouassumethatthereisnobillingdocument
withoutavalidcustomercode(noorphanrows),alltherowsfromthe
tableVBRKplusthecustomershavingnobillingdocumentswillappear
intheresult.Acustomerhavingmultiplebillingdocumentswillhavethat
manyrowsintheresult.Forcustomershavingnobillingdocumentsin
theresult,thefieldsfromthetableVBRKwillcontainINITIALvalues
(blanks,zeros,etc.).
Youwillusethesamedatasourcesforyourtwohandsoninnerjoinand
leftouterjoin.Youcanthencompareresults.
HandsOnExerciseInnerJoin
Thefirstofthehandsonexerciseisoninnerjoin.Youaredeliberately
usingadatabaseviewastheleftsourceinsteadofthetableKNA1to
demonstratetheusageofdatabaseviewinjoinSELECTstatement.The
databaseviewyoucreatedinChapter5containsyourfrequentlyused
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
11/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
fieldsfromtableKNA1andcountrytextfieldLANDXfromthetable
T005T.TheviewnameisYCL_CH05_KNAT5T.Therightsourceisthe
tableVBRK.
Youinputthecustomercodeinbothofthehandsonexercisesforinner
joinandleftouterjoin.Youarefetchingcustomercodeslessthanor
equaltothisvalue.Thisistolimittheoutputastobeabletocompare
resultsofinnerjoinandleftouterjoinmoreeasily.
Theoutputlayout:
Table83.Program:YCL_CH08_09_INNER_JOINOutput
Layout
Field
Description
Name
Column
Positions
SY=TABIX
SerialNumber
005009(5)
KUNNR
CustomerCode
011020(10)
NAME1
CustomerName
022056(35)
LANDX
Country
058072(15)
VBELN
BillingDocument
074083(10)
Number
FKDAT
BillingDocumentDate
085094(10)
Youhavethesameoutputlayoutforthehandsonexerciseofinnerjoin
andleftouterjoin.SoyouhaveacommonINCLUDEprogramtooutput
thelistheaders.
INCLUDEprogramsourcecode:(YCL_CH08_08_HEADER_JOINS)
***********************
TOPOFPAGE.
WRITE:/5TEXT001,TEXT010,93(3)SYPAGNO.
WRITE:/5(90)SYULINE.
WRITE:/5TEXT002,12TEXT003,24TEXT004,59TEXT005,
74TEXT006,85TEXT007.
WRITE:/6TEXT008,13TEXT009.
WRITE:/5(90)SYULINE.
Themainprogramsourcecode:
REPORTYCL_CH08_09_INNER_JOINNOSTANDARDPAGEHEADING
LINESIZE100LINECOUNT60.
**********************************************************
*INNERJOINWithCustomerPrimaryData&BillingDocs.**
**********************************************************
**************************************
*declareTYPES,DATA**
*inputcustomercodePARAMETERS**
***
*INCLUDEheading**
***
*SELECTstatementusingINNERJOIN**
*intointernaltableforcustomer**
*lessthanorequaltoinput**
*customer**
***
*sortinternaltableonKUNNR**
***
*outputfrominternaltable**
**************************************
TYPES:BEGINOFCUST_BILLS_TYPE,
KUNNRTYPEKNA1KUNNR,
NAME1TYPEKNA1NAME1,
LANDXTYPET005TLANDX,
VBELNTYPEVBRKVBELN,
FKDATTYPEVBRKFKDAT,
ENDOFCUST_BILLS_TYPE.
DATA:CUST_BILLSTYPESTANDARDTABLEOFCUST_BILLS_TYPE
WITHHEADERLINE.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
12/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
PARAMETERS:CUST_CDTYPEVBRKKUNAGVALUECHECK
DEFAULT'0000001000'.
*************************************************
INCLUDEYCL_CH08_08_HEADER_JOINS.
STARTOFSELECTION.
SELECTVW~KUNNRVW~NAME1VW~LANDXTB~VBELNTB~FKDAT
INTOCORRESPONDINGFIELDSOFTABLECUST_BILLS
FROM(YCL_CH05_KNAT5TASVW
INNERJOINVBRKASTBONVW~MANDT=TB~MANDT
ANDVW~KUNNR=TB~KUNAG)
WHEREVW~KUNNR<=CUST_CD.
SORTCUST_BILLSBYKUNNR.
LOOPATCUST_BILLS.
WRITE:/5(5)SYTABIX,CUST_BILLSKUNNRUSINGNOEDITMASK,
CUST_BILLSNAME1,CUST_BILLSLANDX,CUST_BILLSVBELN,
CUST_BILLSFKDAT.
ENDLOOP.
ThetextsymbolsfortheheadingareshowninFigure810.
Figure810.Program:YCL_CH08_09_INNER_JOINText
Symbols
TheoutputwillappearlikeFigure811.
Figure811.Program:YCL_CH08_09_INNER_JOINOutput
ForKUNNR<=0000001000,36rowshaveappearedintheoutputas
showninFigure811.
HandsOnExerciseOuterJoin
Youwillusethesamesourceofdataasfortheinnerjoin:databaseview
YCL_CH05_KNAT5TanddatabasetableVBRK.Youwilloutputthesame
fields,sotheoutputlayoutofTable83canbeadopted.
Intheinnerjoinprogram,yousortedtheinternaltablebeforeoutput.In
theresultoftheouterjoin,therowsexistinginboththesourceswill
appearfirstfollowedbytherowsintheleftsidesourcehavingno
correspondingrowsintherightsidesource(i.e.,customershaving
billingdocumentsfirst),followedbycustomershavingnobilling
documents.Inthishandsonexercise,youarenotsortingthedata
generatedbytheouterjoinstatement.Soyouroutputwill,first,haveall
therowswithbillingdocuments,followedbytherowshavingnobilling
documents.ThefieldsVBELNandFKDATintherowshavingnobilling
documentswillcontainINITIALvalues.Thisisreflectedintheoutput.
Thesourcecode:
REPORTYCL_CH08_10_OUTER_JOINNOSTANDARDPAGEHEADING
LINESIZE100LINECOUNT60.
**********************************************************
*OUTERJOINWithCustomerPrimaryData&BillingDocs.**
**********************************************************
**************************************
*declareTYPES,DATA**
*inputcustomercodePARAMETERS**
***
*INCLUDEheading**
***
*SELECTstatementusingOUTERJOIN**
*intointernaltableforcustomer**
*lessthanorequaltoinput**
*customer**
***
*sortinternaltableonKUNNR**
***
*outputfrominternaltable**
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
13/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
**************************************
TYPES:BEGINOFCUST_BILLS_TYPE,
KUNNRTYPEKNA1KUNNR,
NAME1TYPEKNA1NAME1,
LANDXTYPET005TLANDX,
VBELNTYPEVBRKVBELN,
FKDATTYPEVBRKFKDAT,
ENDOFCUST_BILLS_TYPE.
DATA:CUST_BILLSTYPESTANDARDTABLEOFCUST_BILLS_TYPE
WITHHEADERLINE.
PARAMETERS:CUST_CDTYPEVBRKKUNAGVALUECHECK
DEFAULT'0000001000'.
*************************************************
INCLUDEYCL_CH08_08_HEADER_JOINS.
STARTOFSELECTION.
SELECTVW~KUNNRVW~NAME1VW~LANDXTB~VBELNTB~FKDAT
INTOCORRESPONDINGFIELDSOFTABLECUST_BILLS
FROM(YCL_CH05_KNAT5TASVW
LEFTOUTERJOINVBRKASTBONVW~MANDT=TB~MANDT
ANDVW~KUNNR=TB~KUNAG)
WHEREVW~KUNNR<=CUST_CD.
*SORTCUST_BILLSBYKUNNR.
LOOPATCUST_BILLS.
WRITE:/5(5)SYTABIX,CUST_BILLSKUNNRUSINGNOEDITMASK,
CUST_BILLSNAME1,CUST_BILLSLANDX,CUST_BILLSVBELN,
CUST_BILLSFKDAT.
ENDLOOP.
Thetextsymbols:
Figure812.Program:YCL_CH08_10_OUTER_JOINText
Symbols
TheoutputwillappearlikeFigure813.
Figure813.Program:YCL_CH08_10_OUTER_JOINOutput
Therowhighlightedinblack(serialnumber36)isthelastrowthathasa
rowexistingintheleftsidesourceaswellastherightsidesource.From
thenextrowonwarduntiltheend(serialno112),rowsoftheleftside
sourcedonothaveanycorrespondingrowsintherightsidesource.The
fieldsVBELNandFKDAThaveINITIALvaluesreflectedintheoutputin
Figures813and814.
Figure814.Program:YCL_CH08_10_OUTER_JOINEndof
Output
HandsOnExerciseSubquery
YoucanspecifyaSELECTstatementintheWHEREandHAVING
clauses(SELECTwithinaSELECT),calledsubqueries.
ThesubquerycannothaveINTOandORDERBYclauses.Youcannest
subqueries.ThesubquerycannotbegivenintheON<condition>ofjoin
clause.Subqueriescanbescalarornonscalar.Scalarsubquerieswill
haveonlyonefieldoraggregatefunctioninthesubquerySELECT
statement.
Ascalarsubquerycanreturneitheronerowormultiplerows.Ifascalar
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
14/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
subqueryreturnsasinglerow(maybewithSELECTSINGLE),itmust
havethefollowingcomparisonsyntax:
...<sourcefield><operator><subquery>...
Ifascalarsubqueryreturnsmultiplerows,itmusthavethefollowing
comparisonsyntax:
...<sourcefield><operator>ALL|ANY|SOME<subquery>...
IfyouusetheALLprefix,theconditionistrueonlyifthecomparisonis
trueforalltherowsinthesubquery.IfyouuseANYorSOMEprefix,the
conditionistrueonlyifthecomparisonistrueforatleastonerowofthe
subquery.Theequalityoperator(=orEQ)inconjunctionwithANYor
SOMEhasthesameeffectastheINoperatorforcheckingavalue.
Youaredemonstratingasimplescalarsubquery.Youhaveascenario
whereyouneedtooutputbillingdocumentsdataforcustomersofa
specifiedcity.SoyourSELECTstatementinvolvingthedatabasetables
VBRK,KNA1wouldbelikethis:
SELECTVBELNFKDATKUNAGWAERKNETWRFROMVBRK
INTOTABLEBILLS_TAB
WHEREKUNAGIN(SELECTKUNNRFROMKNA1WHEREORT01='Berlin').
ThiswillreturnallbillingdocumentrowsfromVBRKforcustomercodes
havingORT01value=BerlininthetableKNA1.
Theprogramsourcecode:
REPORTYCL_CH08_11_SUBQUERYNOSTANDARDPAGEHEADING
LINESIZE90LINECOUNT60.
****************************************************
*SELECTstatementinWHEREcondition:Subquery**
****************************************************
************************************
*declaredata.inputcity.**
*codeheading**
***
*loadinternaltablefromtable**
*VBRKusingsubqueryinSELECT**
*statement.**
***
*sortinternaltablebyVBELN**
*outputfrominternaltable**
************************************
DATA:BEGINOFBILL_STRU,
VBELNTYPEVBRKVBELN,
FKDATTYPEVBRKFKDAT,
KUNAGTYPEVBRKKUNAG,
WAERKTYPEVBRKWAERK,
NETWRTYPEVBRKNETWR,
ENDOFBILL_STRU,
BILL_TABLIKESTANDARDTABLEOFBILL_STRU.
PARAMETERS:ORT01TYPEORT01_GPLOWERCASE"referencetodataelement
DEFAULT'Berlin'.
****************************************************************
*try:Frankfurt,Hamburg,Bonn,SanFrancisco,NEWYORKetc.**
*notethecasesensitivityoffieldORT01**
****************************************************************
TOPOFPAGE.
WRITE:/5TEXT001,ORT01,66(3)SYPAGNO.
SKIP.
WRITE:/5(63)SYULINE.
WRITE:/5TEXT002,11TEXT003,22TEXT004,33TEXT005,
56TEXT006,64TEXT007.
WRITE:/6TEXT008,34TEXT009.
WRITE:/5(63)SYULINE.
****************************************************************
STARTOFSELECTION.
SELECTVBELNFKDATKUNAGWAERKNETWRFROMVBRKINTOTABLEBILL_TAB
WHEREKUNAGIN(SELECTKUNNRFROMKNA1WHEREORT01=ORT01).
SORTBILL_TABBYVBELN.
LOOPATBILL_TABINTOBILL_STRU.
WRITE:/5(4)SYTABIX,BILL_STRUVBELN,BILL_STRUFKDAT,
BILL_STRUKUNAGUSINGNOEDITMASK,
BILL_STRUNETWR,BILL_STRUWAERK.
ENDLOOP.
ThetextsymbolsusedintheheaderareshowninFigure815.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
15/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
Figure815.Program:YCL_CH08_11_SUBQUERYText
Symbols
TheOutputisshowninFigure816.
Figure816.Program:YCL_CH08_11_SUBQUERYOutput
TabularWHERECondition
Considerthescenario:youhavetwointernaltables,onedesignatedas
primaryandthesecondonedesignatedassecondary.Intotheprimary
internaltable,youhaveretrieveddatafromadatabasetableorview.
Nowyouwanttoretrieveintothesecondaryinternaltableonlythedata
thatisrelatedtothedataintheprimaryinternaltable.
Letthisscenariobeintermsofspecificdatabasetables.Supposeyouhave
retrievedintotheprimaryinternaltable(named,say,PITAB)datafrom
thedatabasetableVBRK(billingdocumentsheader)forspecific
customercodes.Theprimaryinternaltablewillcontaindatapertaining
tosomebillingdocumentnumbers(documentnumberispartofthe
primarykeyintableVBRK).Nowyouwanttoretrievedatafromthetable
VBRP(billingdocumentsitems)intothesecondaryinternaltable,
belongingtoorrelatedtothebillingdocument,anumberrowsinthe
primaryinternaltable(named,say,SITAB).
ThisiswherethetabularWHEREconditioncomesinhandy.TheTabular
WHEREconditionwillbeusedforretrievingdataofthesecondary
internaltable.
Thesyntaxforatabularcondition:
SELECT...FORALLENTRIESIN<primaryinternaltable>WHERE<condition>...
FORALLENTRIESINinakeyphrase.
Inyourdescribedscenario,thiswouldbelike:
SELECT...FROMVBRPINTOTABLESITABFORALLENTRIESINPITAB
WHEREVBELN=PITABVBELN.
Thesemanticsofthis:retrieverowsfromVBRPintoSITABonlyof
VBELNvaluesthatareresidingintheinternaltablePITAB.
Theprogramsourcecode:
REPORTYCL_CH08_12_TABULAR_CONDITION.
****************************
*TabularWHERECondition**
****************************
*******************************************************
*trythiswithcustomercodes:473,401081**
***
*thefollowingbillingdocumentswillbeloaded**
*intoprimaryinternaltablePITAB**
***
*customercodebillingdocumentno.**
*(KUNAG)(VBELN)**
***
*4730090026209**
*4730090029855**
***
*4010810090032165**
***
***
*correspondingtothesethreebillingdocuments**
*thefollowingmaterials/itemswillbeloadedinto**
*secondaryinternaltableSITAB**
***
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
16/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
*billingdocumentno.materialcode**
*(VBELN)(MATNR)**
***
*0090026209HT1011**
*0090026209HT1010**
***
*0090029855HT1011**
***
*0090032165HT1040**
***
***
*******************************************************
*******************************************************
*declaredata.promptinputfortwocustomers**
***
*loadprimaryinternaltablewithbillingdocuments**
*oftheinputcustomers**
***
*loadthesecondaryinternaltablewithmaterials/**
*itemsbelongingtothebillingdocumentsinthe**
*primaryinternaltablewiththetabularWHERE**
*condition**
***
*outputfromprimary,secondaryinternaltables**
*******************************************************
DATA:BEGINOFPITAB_STRU,
VBELNTYPEVBELN_VF,
FKDATTYPEFKDAT,
KUNAGTYPEKUNAG,
NETWRTYPENETWR,
WAERKTYPEWAERK,
ENDOFPITAB_STRU,
PITABLIKESTANDARDTABLEOFPITAB_STRU,
BEGINOFSITAB_STRU,
VBELNTYPEVBELN_VF,
MATNRTYPEMATNR,
NETWRTYPENETWR,
ENDOFSITAB_STRU,
SITABLIKESTANDARDTABLEOFSITAB_STRU.
**********************************************************
PARAMETERS:CUST_CD1TYPEVBRKKUNAGVALUECHECK
DEFAULT'473',
CUST_CD2TYPEVBRKKUNAGVALUECHECK
DEFAULT'401081'.
*SELECTOPTIONSCUST_CDSFORPITAB_STRUKUNAG.
************************************************************
STARTOFSELECTION.
SELECTVBELNFKDATKUNAGNETWRWAERKFROMVBRK
INTOTABLEPITABWHEREKUNAGIN(CUST_CD1,CUST_CD2)."INCUST_CDS
SELECTVBELNMATNRNETWRFROMVBRP
INTOTABLESITABFORALLENTRIESINPITAB
WHEREVBELN=PITABVBELN."tabularcondition
LOOPATPITABINTOPITAB_STRU.
WRITE:/5(4)SYTABIX,PITAB_STRUKUNAG,PITAB_STRUVBELN.
ENDLOOP.
SKIP2.
LOOPATSITABINTOSITAB_STRU.
WRITE:/5(4)SYTABIX,SITAB_STRUVBELN,SITAB_STRUMATNR.
ENDLOOP.
YouhaveusedtheINoperatorinthefirstSELECTstatement.Youcould
haveusedWHEREKUNAG=CUST_CD1ORKUNAG=CUST_CD2.
Toenableaneasydemonstration,asmallamountofdatahasbeen
identifiedandselected(i.e.,twocustomershavingfewbilling
documents):twobillingdocumentsforthefirstcustomerandoneforthe
second,atotalofthreebillingdocuments(seetheprogramcomments).
Thebillingdocumentsidentifiedhavefewitems:onebillingdocument
havingtwoitemsandtwootherbillingdocumentshavingasingleitem
atotaloffouritems.
YoucancheckthisdatafortablesVBRKandVBRPinthedatabrowser
SE16transactioncode.Youcanexecutetheprogramwithothercustomer
codesandverifyresults.
TheoutputisshowninFigure817.
Figure817.Program:YCL_CH08_12_TABULAR_CONDITION
Output
ABAPFIELDSYMBOLS
TheABAPFIELDSYMBOLS,whichwillbereferredasfieldsymbols,isa
digressionfromthecoverageofSELECTstatementvariants.Thefield
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
17/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
symbolsenabledynamicaccessofdataobjects.Thefieldsymbolshave
beenpartoftheABAPprocedureorientedlanguage.RTTSRunTime
TYPEServices,afeatureofABAPOOP,enablescreationofruntimedata
objectsorthedynamicdataobjectsthatareunlikethestaticdataobjects
youweredeclaringwithkeywordsDATA,TABLES,etc.Thecombination
ofruntimedataobjectsandfieldsymbolstakeOpenSQLdataretrievalto
adifferentlevelasyouwillseeintheforthcominghandsonexercises.
Untilnowyouwereaccessingdataobjectsinastaticmannerbyusingthe
nameofthedataobjectsorfields.ThefieldsymbolsandABAPOOPdata
referencesenableyoutoaccessdataobjectswhosename,attributes
(TYPE,length,etc.)youknowonlyatruntime.
Thefieldsymbolscanbeassignedtodataobjects.Theyserveasakindof
symbolicnameforthedataobjectsassignedtothem.Whenyouusefield
symbols,thesystemworkswiththecontentsofthedataobjectandnot
withthecontentsofthefieldsymbols.
ABAPOOPdatareferencespointtothedataobjects.Toaccessthe
contentsofadataobjecttowhichABAPOOPdatareferenceispointing,
youmustdereferenceit.
FieldSymbolDeclarations
Thefieldsymbolshavetobedeclaredbeforetheyareassignedtodata
objects.Thefieldsymbolsaredeclaredinthefollowingway:
FIELDSYMBOLS:<FSYBOL1>,<FS>,<FSTRU>.
TheFIELDSYMBOLSisakeywordjustlikeDATA,TYPES,etc.The
nameoffieldsymbolsstartswiththelessthan(<)characterandendswith
thegreaterthan(>)character.Thenamespaceoffieldsymbolsisa
maximumof30charactersincludingtheenclosingcharacters:<>.The
usualnamingconventionsapply:name(after<)hastostartwithan
alphabet,andtherestofthecharacterscanbealphanumericwith
embeddedunderscores(_).
Whiledeclaringfieldsymbols,youcanspecifythetypes,justlikeyoudid
fortheformalparametersofsubroutines.
Youcan,whiledeclaringthefieldsymbols,specifytheABAPpredefined
elementarytypes,localTYPES,globalTYPES(TypeGroupsanddata
elements),localdataobjects,globaldataobjects,andsystemfields.
ReferencecanalsobetothegenericABAPTypes.AlistofgenericABAP
Typescanbefoundintheonlinedocumentationwiththefollowing
navigation:ABAPByTheme
Functions
BuiltInTypes,DataObjectsand
BuiltInDataTypes
GenericABAPTypes.The
keywordsTYPEandLIKEcanbeusedjustlikeintheformalparameters
ofsubroutines.
Ifyoudonotspecifythetypewhiledeclaringfieldsymbols,thefield
symbolswillassumetheattributesoftheassigneddataobjects/TYPE
duringtheassignmentprocesstofieldsymbols.Youcanalsospecify
genericorpartiallygenerictypesforfieldsymbolsduringtheir
declaration.Inthiscase,theexactorremainingattributesofthefield
symbolswillbeinheritedfromdataobjectsorTYPEStowhichField
Symbolisassigned.
Partiallistofgenericandpartiallygenerictypespecificationsduring
fieldsymbolsdeclaration:
Table84.DeclarefieldsymbolsGeneric,PartiallyGenerictypes:
PartialList
Generic/Partially
Description
GenericType
Unspecified/
AnytypeofDataObjectCanBeAssigned
TYPEANY
TYPEC,N,P,X
AnyOneofThem.TheLength,Decimals
IfAnyAreInheritedFromtheAssigned
DataObject
TYPETABLE
StandardInternalTableCanBe
Assigned
TYPE
STANDARD
TABLE
TYPEANY
StandardTableorSortedTableor
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
18/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
TABLE
IndexedTableorHashedTableCanBe
Assigned
TYPEINDEX
StandardTableorSortedTableCanBe
TABLE
Assigned
TYPESORTED
SortedTableCanBeAssigned
TABLE
TYPEHASHED
HashedTableCanBeAssigned
TABLE
FieldsymbolsdeclarationsusinggenericorpartiallygenericTYPES:
FIELDSYMBOLS:<ANY1>TYPEANY,
<ANY2>,
<ELEM1>TYPEC,
<ELEM2>TYPEP,
<STABL>TYPETABLE,
<ATABL>TYPEANYTABLE,
<STAB>TYPESORTEDTABLE.
ListoffullyspecifiedTYPEduringFieldSymbolsDeclaration:
Table85.DeclarefieldsymbolsSpecifytypesfully
Fully
Description
Specified
TYPE
TYPED,F,
AnyOneofThem
I,T
TYPE
DeclarationInABAPProgramWithTYPES
<type>
DDICTypeGroup
DDICDataElement
OtherDDICGlobalDataObjects:Table,
Structure,Table/StructureField
TYPE<data
Internal,External,System,SpecialData
object>
Object
TYPEREF
ReferenceVariable,ReferringTo
TO
Class/Interface
TYPE/LIKE
StructureOfInternalTable
LINEOF
FieldsymbolsdeclarationusingfullyspecifiedTYPES:
DATA:NAME(25)TYPEC,
CURR_TABTYPESTANDARDTABLEOFTCURT.
PARAMETERSDAY(9)TYPEC.
FIELDSYMBOLS:<DATE>TYPED,
<INT4>TYPEI,
<TYP1>TYPEKUNNR,
<TYP2>TYPEVBRKNETWR,
<DOBJ1>LIKENAME,
<DOBJ2>LIKEDAY,
<TLINE>LIKELINEOFCURR_TAB.
FieldSymbolStaticAssignments
Youcanassignorreassignafieldsymboltodataobjects.Ifthefield
symbolspecifiedtypedoesnotmatchwiththeassigneddataobjecttype,a
syntaxerrororruntimeerroristriggered,dependingontheassignment
beingdonetoastaticordynamicdataobject.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
19/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
Iftheassignmentissuccessful,thesystemfieldSYSUBRCissettozero
orelsetononzero.
Fieldsymboldeclarations,assignments:
DATA:CURR_TABTYPESTANDARDTABLEOFTCURT
WITHHEADERLINE.
FIELDSYMBOLS:<ITAB>TYPEANYTABLE,
<TLINE>LIKELINEOFCURR_TAB,
<FIELD>.
ASSIGN:CURR_TAB[]TO<ITAB>,
CURR_TABTO<TLINE>,
CURR_TABLTEXTTO<FIELD>
ASSIGNisthekeywordtoassigndataobjectstoFieldSymbols.
FollowingthekeywordASSIGN,youspecifythenameofthedataobject
tobeassignedandthekeywordTObefollowedbythenameofthefield
symboltowhichyouwanttoassignthedataobject.
Inthesecodelines:
Whenyouuse<ITAB>orCURR_TAB[],youareaccessingthesamedata
objectandtheinternaltableCURR_TAB.
Whenyouuse<TLINE>orCURR_TAB,youareaccessingthesame
structuredataobjectCURR_TAB.
Whenyouuse<FIELD>or<TLINE>LTEXTorCURR_TABLTEXT,
youareaccessingthesamedataobjectasthefieldLTEXTofstructure
CURR_TAB.
YoucanusetheoffsetsandlengthsincaseofTYPESC,D,N,andT.
Youcanalsoassignonefieldsymboltoanother.
Inthisexample,thestructureCURR_TABdeclaredwiththekeyword
DATAisastaticdataobject.Ifyourstructuredataobjectisnotstatic(i.e.,
youdonotknowittillruntime),youcanaccessitsfieldsorcomponents
withanothervariationoftheASSIGNstatement.
ASSIGNCOMPONENT<componentnumber>OFSTRUCTURE<structurename>
TO<fieldsymbolname>.
<componentnumber>isthesequencenumberofthefieldinthe
structure.Itcanbeeitherliteral/variable.
<structurename>isthenameofthestructureornameofanotherField
Symbolassignedtoastructure.
<fieldsymbolname>isthefieldsymboltowhichassignmentisbeing
made.
Inyourprecedingexample,ifyouhadwritten:
ASSIGNCOMPONENT4OFSTRUCTURECURR_TABTO<FIELD>.
Itisequivalentto:
ASSIGN:CURR_TABLTEXTTO<FIELD>
ThefourthfieldofstructureCURR_TABisLTEXT.
Thesearestaticassignments.Thedataobjecttowhichassignmentsare
madeispredetermined.
FieldSymbolHandsOnExercise
Letthefieldsymbolsbeappliedinahandsonexercise.Untilnow,inthe
contextofinternaltables,youwerealwaysretrievingarowofdatafrom
theinternaltableintoaworkareaorheaderline(i.e.,astructureand
operatingonthecontentsofthestructurelikeoutput,etc.).Withthehelp
offieldsymbolsyoucandirectlyoperateontherowintheinternaltable
withoutfetchingitintoastructure.Thedefinitionofaseparatestructure
isuncalledfor.Considerthecodelines:
DATA:CURR_TABTYPESTANDARDTABLEOFTCURT.
FIELDSYMBOLS:<ROW_POINTER>LIKELINEOFCURR_TAB.
SELECT*FROMTCURTINTOTABLECURR_TABWHERESPRAS=SYLANGU.
LOOPATCURR_TABASSIGNING<ROW_POINTER>.
WRITE:/5(4)SYTABIX,<ROW_POINTER>WAERS,<ROW_POINTER>LTEXT.
ENDLOOP.
TheLOOP...ENDLOOPconstructisdifferentfromtheonesyouwere
using.Inthisconstruct,youarenotfetchingarowfromtheinternaltable
intothestructureforeachpassoftheloop(thereisnoworkarea/header
linedeclared).Rather,thefieldsymbol<ROW_POINTER>isaccessing
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
20/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
thecontentsofinternaltablesfirstrowdirectlyduringthefirstpassof
theloop,thecontentsofthesecondrowduringthesecondpassofthe
loop,andsoonuntilalltherowshavebeenaccessed.Itislikeduring
eachpassoftheloop,thecorrespondingrowistheworkarea.
IfyouareprocessingverylargevolumeofdatawithaLOOPENDLOOP
construct,thisisthepreferredwayofdoingit.Itsavestheoverheadof
movingdatafromtheinternaltableintostructure,resultinginreduced
executiontime.
AhandsonusingthisnotationofLOOPENDLOOPwillbeperformed
usingthedatafromthecustomerprimarytableKNA1.
Youwillcodetwoprogramstoprovideacomparisonofexecutiontimes.
ThetwoprogramsareidenticalexceptfortheLOOPENDLOOP
construct.ThefirstprogramYCL_CH08_13_CUST_LIST_WITHSTRU
generatesacustomerlistwithaLOOPATINTOnotation.Thesecond
programYCL_CH08_14_CUST_LIST_WOUTSTRUgeneratesa
customerlistwithaLOOPATASSIGNINGnotation.
AstatementGETRUNTIMEisusedtogettheexecutiontimeinmicro
secondsinboththeprograms.Thestatementiselaboratedinthe
commentlinesoftheprograms.Thefirstprogramisnotlistedhere,asits
codeisobvious.ItisavailableinEResource.Thesecondprogram
YCL_CH08_14_CUST_LIST_WOUTSTRUislistedhere:
REPORTYCL_CH08_14_CUST_LIST_WOUTSTRULINESIZE140LINECOUNT60
NOSTANDARDPAGEHEADING.
*************************************************************
*ListCustomersUseFieldSymbolToAccessRowDirectly**
*NoWorkArea/HeaderLine**
*************************************************************
****************************************************
*theGETRUNTIMEstatementisusedtoascertain**
*theexecutiontimeforaprogramblockinmicro**
*seconds.thefirsttimeitisexecuted,it**
*assignszerotothespecifiedvariable.from**
*thesecondandsubsequentoccurrences,itloads**
*/assignscumulativeelapsedtimeinmicro**
*seconds.**
***
*soyoucandeterminetheexecutiontimeofa**
*programblockbysubtractingthevalueassigned**
*atthebeginningofprogrammingblockfromthe**
*valueassignedattheendoftheprogramming**
*block(difference)**
****************************************************
DATA:TIME_ELAPSEDTYPEIVALUE100,
DATE_CHR(10)TYPEC.
DATA:CUSTOMERS_TABLIKESTANDARDTABLEOF
YCL_CH05_CUST_STRU.
FIELDSYMBOLS:<FS1>LIKELINEOFCUSTOMERS_TAB.
"specifyingTYPE/LIKEtostaticdataobject
************************************************
TOPOFPAGE.
WRITE:/5TEXT001,DATE_CHR,130TEXT002,137(3)SYPAGNO.
SKIP1.
WRITE:/5(135)SYULINE.
WRITE:/6TEXT003,12TEXT004,23TEXT005,60TEXT006,96
TEXT007,130TEXT008.
WRITE:/6TEXT009,13TEXT010,131TEXT010.
WRITE:/5(135)SYULINE.
************************************************
STARTOFSELECTION.
GETRUNTIMEFIELDTIME_ELAPSED.
CONCATENATESYDATUM+6(2)SYDATUM+4(2)SYDATUM+0(4)INTODATE_CHR
SEPARATEDBY'/'.
SELECTKUNNRNAME1STRASORT01PSTLZFROMKNA1
INTOTABLECUSTOMERS_TAB.
SORTCUSTOMERS_TABBYKUNNR.
LOOPATCUSTOMERS_TABASSIGNING<FS1>.
"<FS1>addresses/accessesfirstrow,secondrow&soon
WRITE:/5(5)SYTABIX,<FS1>KUNNRUSINGNOEDITMASK,
<FS1>NAME1,<FS1>STRAS,"structurecomponents/fieldsare
<FS1>ORT01,<FS1>PSTLZ."addressablebecause<FS1>TYPEtostaticdataobject
ENDLOOP.
GETRUNTIMEFIELDTIME_ELAPSED.
SKIP2.
WRITE:/5'Timeelapsed:',(7)TIME_ELAPSED.
ThetextsymbolsareshowninFigure818.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
21/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
Figure818.Program:
YCL_CH08_14_CUST_LIST_WOUTSTRUTextSymbols
TheoutputofprogramYCL_CH08_13_CUST_LIST_WITHSTRU(LOOP
ATINTO)isshowninFigures819and820.
Figure819.Program:YCL_CH08_13_CUST_LIST_WITHSTRU
Output
Figure820.Program:
YCL_CH08_13_CUST_LIST_WITHSTRUOutput
TheoutputofprogramYCL_CH08_14_CUST_LIST_WOUTSTRU
(LOOPATASSIGNING)isshowninFigures821and822.
Figure821.Program:
YCL_CH08_14_CUST_LIST_WOUTSTRUOutput
Figure822.Program:
YCL_CH08_14_CUST_LIST_WOUTSTRUOutput
ThesyntaxandnotationoftheAGGIGNING<fieldsymbol>canbeused
intheinternaltablesREADstatements.Youcandirectlyaccessarow
throughtheREADstatementwithanASSIGNINGnotation.Youcanalso
directlyassignvaluestofieldsofarowtowhichtheFieldSymbolis
pointing,thusavoidingtheMODIFYstatementyouusedearliertoalter
thecontentsofinternaltablerows.TheuseoftheMODIFYstatement
involvestransferofdatafromthetableintothestructureandthenfrom
thestructuretothetable.WiththeASSIGNINGnotation,thesetransfers
canbeavoided.Thesefeaturesaredemonstratedintheprograms:
YCL_CH08_15_READ_KEY_ASSIGN,
YCL_CH08_16_READ_INDEX_ASSIGN,and
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
22/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
YCL_CH08_17_CHANGE_WOUT_MODIFY.Theseprogramsarenot
listedhere,butyoucanfindthemintheEResource.
FieldSymbolDynamicAssignments,UNASSIGN,CheckIfAssigned
Youcandecideatruntime,whatdataobjectistobeassignedtoafield
symbol.Thisiscalleddynamicassignment.Thesyntaxfordynamic
assignment:
ASSIGN:(<variablename>)TO<FieldSymbol>.
<variablename>willcontainthenameoftheruntimefieldtowhichyou
wanttoassignthe<FieldSymbol>.The<variablename>hastobe
enclosedinparentheses.Youcannotuseoffsetsandlengthwithdynamic
assignments.
YoucanunassignaFieldSymbol.Thesyntax:
UNASSIGN:<FieldSymbol>.
YoucancheckintheIFconditionstatementwhetherafieldsymbolis
assignedornot:
IF<FieldSymbol>ISASSIGNED.
YoucanrefertothistopicinthePDFdocumentABAPProgramming
(BCABA).
YouwillseethepowerofFieldSymbolsinthecurrentandforthcoming
Chapters10,12,and13.
Aswitchbacktothemaintopic:OpenSQLSELECTstatementvariants.
Specifythe<source>InOpenSQLSELECTStatementatRuntime
TheOpenSQLSELECTstatementallowsthe<source>(i.e.,thedatabase
table/view)fromwhichdataistoberetrievedtobespecifiedatruntime.
Associatedwiththeruntimespecificationofthesourceandthe
<destination>(followingthekeywords:INTO/APPENDING,etc.),not
knownuntilruntimecannotbedeclared/definedstaticallywithDATA
andTABLESstatements.The<destination>dataobject
(structure/internaltable)needstobecreateddynamicallyatruntime.
CreateDynamicDataObjects
TheABAPOOPfeature(runtimetypeservices)RTTSprovidesforthe
creationofruntimedataobjects..RTTSwillbecoveredinmoredetailin
Chapter11entitledABAPOOP,butheresashortintroductionsothatyou
canseehowitsusedintheOpenSQLSELECTstatement.Tocreatea
runtimedataobjectusingRTTS:
YouhavetodeclareareferencevariableusingthekeywordDATA
likethis:
DATA:RF_VARTYPEREFTODATA.
RF_VARisthenameoftheABAPreferencevariablefollowingthe
namingconventionsofanyotherABAPvariable.
TYPEREFTODATAisakeyphrase,indicatingthatthisreference
variablewillpointtotheruntimedataobjecttobecreated.
Usingthedeclaredreferencevariable,youhavetocreatethe
runtimedataobject:
CREATEDATARF_VAR{TYPE/LIKE}<referredobject>.
<referredobject>canbeanylocal/DDICTYPESoranyofthe
local/DDICdataobjects.
Forexample,ifyouwanttocreateadynamicdataobjectthesameasthe
DDICtablestructureKNA1,youshouldbewriting:
CREATEDATARF_VARTYPEKNA1.
Butagainyouarehardcoding.Thiswillcreateonlyadataobjectlikethe
tablestructureKNA1,notanyother.Hence,youhavetouseanother
variationofthestatementCREATEDATAThecodewillbelikethis:
DATA:RF_VARTYPEREFTODATA.
PARAMETERS:OBJ_NAME(50)TYPECDEFAULT'KNA1'.
STARTOFSELECTION.
CREATEDATARF_VARTYPE(OBJ_NAME).
ThiswillcreatearuntimedataobjectoftheTYPEwhosenameis
containedinthevariableOBJ_NAME(inputthroughthePARAMETERS
statement).Whateverobjectnameyouenterintheinputvariable
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
23/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
OBJ_NAME,theCREATEDATAstatementwillcreateadataobjectof
thatTYPE.Thereferencevariablepointstothisdataobject,nottothe
contentsofthedataobject.Youneedtoaccessthecontents.Oneway
doingthisthatis,togetaccesstocontentsistodereferencethe
referencevariableRF_VARandassignittoafieldsymbol.Thecodeto
dothiswillbelikethis:
DATA:RF_VARTYPEREFTODATA.
FIELDSYMBOLS:<DOBJ>.
PARAMETERS:OBJ_NAME(50)TYPECDEFAULT'KNA1'.
STARTOFSELECTION.
CREATEDATARF_VARTYPE(OBJ_NAME).
ASSIGNRF_VAR>*TO<DOBJ>.
The>*istodereference.
RunTime<source>SpecificationinSELECTStatementHandson
Havingbeenintroducedtothebareessentialsofthecreationofdynamic
dataobjects,letahandsanexercisebeperformed.
IntheABAPprogram,letthedatabasetableorviewnamefromwhichthe
dataistoberetrievedbeinputthroughthePARAMETERSstatement.
Usingthisinput,youwillcreatetwodynamicdataobjects:(a)astructure,
and(b)aninternaltable.
Youwillloaddatafromthedatabasetableorviewintotheinternaltable.
YouwilluseLOOPENDLOOPconstructtoretrievedatafromthe
internaltableintoastructure.Asyoudonotknowthefieldnames,you
willusetheASSIGNCOMPONENTvariationoftheASSIGNfieldsymbol
statementtoaccessindividualfields.Youwilloutputthefirstfivefields.
Thesourceprogram:
REPORTYCL_CH08_18_SRCE_AT_RUN_TIMELINESIZE150
NOSTANDARDPAGEHEADING.
*******************************************************
*<source>InSELECTAtRuntime,DynamicDataObjects*
*******************************************************
*************************************************
*fromwhichdatabasetable/viewtoretrieve**
*dataisdecidedatruntime.**
***
*theruntimedatabasetablenameisinput**
*throughPARAMETERSstatement.(TABLE_NM)**
***
*whenyouareretrievingdatafromadatabase**
*table/viewintoaninternaltable,the**
*internaltablemusthaveastructurewhich**
*canaccommodatetheretrievedfields.(all**
*fieldsofdatabasetable/viewfornow)**
***
*whenyouareretrievingdata,onerowata**
*timefromtheinternaltableintoastructure**
*youdonotknowthestructure'sattributes**
*intermsoffields/componentstillruntime**
***
*soyouarecreatingadynamicstructuredata**
*objectusingthetable/viewnameinput.**
*thewaytocreatedynamicstructuredata**
*objectis:**
*(a)declareusingDATAstatementareference**
*variablelike:**
*DATASTRU_REFTYPEREFTODATA.**
*(b)createdynamicstructuredataobjectby**
*referringtotheinputtable/viewname**
*like:**
*CREATEDATASTRU_REFTYPE(TABLE_NM).**
***
*thiswillcreateastructuredataobject**
*havingthesamefieldsasthetable/view**
*inputinTABLE_NM.ifforInstance,KNA1**
*wasinput,theCREATEDATASTRU_REFTYPE**
*(TABLE_NM).willcreateastructuredata**
*objecthavingallthefieldsoftable**
*structureKNA1.thereferencevariable**
*STRU_REFwillpointtothestructuredata**
*object.**
***
*tobeabletorefer/pointtothedata**
*youneedtodereferencethereference**
*variableSTRU_REF.youaredereferencingand**
*assigningtoaFieldSymbol<FS_STRU>like**
*ASSIGNSTRU_REF>*TO<FS_STRU>.**
***
*youarecreatingadynamicinternaltable**
*dataobjectusingthetable/viewnameinput.**
*thewaytocreatedynamicinternaltable**
*dataobjectis:**
*(a)declareusingDATAstatementareference**
*variablelike:**
*DATAITAB_REFTYPEREFTODATA.**
*(b)createdynamicinternaltabledataobject**
*byreferringtotheinputtable/view**
*namelike:**
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
24/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
*CREATEDATAITAB_REFTYPESTANDARDTABLE**
*OF(TABLE_NM).**
***
*thiswillcreateainternaltabledataobject**
*havingthesamefieldsasthetable/view**
*inputinTABLE_NM.ifforinstance,KNA1**
*wasinput,theCREATEDATAITAB_REFTYPE**
*STANDARDTABLEOF(TABLE_NM).willcreatean**
*internaltabledataobjecthavingallthe**
*fieldsoftablestructureKNA1.thereference**
*variableITAB_REFwillpointtotheinternal**
*tabledataobject.**
***
*tobeabletorefer/pointtothedatainthe**
*internaltable,youneedtodereferencethe**
*referencevariableITAB_REF.youare**
*dereferencingandassigningtoaFieldSymbol**
*<FS_ITAB>like:**
*ASSIGNITAB_REF>*TO<FS_ITAB>.**
***
*toaccesstheindividualfieldsofstructure**
*youareusingtheFieldSymbolassignment**
*statementform:**
*ASSIGNCOMPONENT<componentnumber>OF**
*<structurename>TO<fieldsymbolname>.**
***
*theindividualfieldsaccessedinthisway**
*areoutput.**
***
*theconceptofcreatingdynamicdataobjects**
*isbeingintroducedinapreviewmanner.it**
*iscoveredwithintheregularcoursein**
*Chapter10.**
*************************************************
*************************************************
*inputthetable/viewnamefromwhichdatato**
*beretrieved**
***
*createadynamicstructuredataobjectof**
*typesameastheinputtedtable/view.**
*deferenceandassigntoFieldSymbol**
***
*createadynamicinternaltabledataobject**
*whosestructuretypeissameastheinputted**
*table/view.**
*deferenceandassignToanotherFieldSymbol**
***
*usetheSELECTstatementvariationwith**
*runtime<source>tofetchdataintodynamic**
*internaltabledataobject**
***
*setupLOOP...ENDLOOP**
***
*assignindividualfieldsofstructuredata**
*objecttoanotherFieldSymbol&output**
***
*LOOP...ENDLOOPwillrunthroughtillall**
*rowsfetched&outputted**
*************************************************
DATA:STRU_REFTYPEREFTODATA,"referencevariableforstructure
ITAB_REFTYPEREFTODATA."referencevariableforinternaltable
FIELDSYMBOLS:<FS_STRU>,"FieldSymbolfortable/viewstructure
<FS_ITAB>TYPETABLE,"FieldSymbolforinternaltable
<FS_FLD>."FieldSymbolforindividualfields
PARAMETERSTABLE_NMTYPEDD03LTABNAMEDEFAULT'T001'VALUECHECK.
*******************************************************************
STARTOFSELECTION.
CREATEDATASTRU_REFTYPE(TABLE_NM)."creationofruntimestructure
ASSIGNSTRU_REF>*TO<FS_STRU>."dereferenceandassigntoFieldSymbol
CREATEDATAITAB_REFTYPESTANDARDTABLEOF(TABLE_NM)."creationofruntimeinternaltable
ASSIGNITAB_REF>*TO<FS_ITAB>."dereferenceandassigntoFieldSymbol
SELECT*FROM(TABLE_NM)INTOTABLE<FS_ITAB>."sourceatruntime
LOOPAT<FS_ITAB>INTO<FS_STRU>.
DO6TIMES.
IFSYINDEX=1."bypassthepresumedclientcode(first)field
CONTINUE.
ENDIF.
ASSIGNCOMPONENTSYINDEXOFSTRUCTURE<FS_STRU>TO<FS_FLD>.
"FieldSymbol<FS_FLD>beingassigned&reassigned
IFSYINDEX=2.
WRITE:/5<FS_FLD>."newlineforthefirstoutputtedfield
ELSE.
WRITE:<FS_FLD>.
ENDIF.
ENDDO.
ENDLOOP.
TheoutputfortheinputvalueT001willlooklikeFigure823.
Youcantrythisforafewothertables.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
25/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
Figure823.Program:YCL_CH08_18_SRCE_AT_RUN_TIME
Output
YouhaveseenthepowerofSELECTstatement,fieldsymbolsand
dynamicdataobjectsincombinationinthisprogram.
InChapter10entitledInteractiveLists,youwillincorporatefurther
functionalityintothisprogram.Theprogramoninputofdatabasetable
orviewnamewillfirstdisplayallthefieldsofthetableorviewstructure
withcheckboxesfortheusertoselect/deselectfields.Oncethefieldsare
selected,theprogramwillretrievedataonlyfortheselectedfieldsand
outputtheselectedfieldswithcolumnheadings,etc.
SpecifyintheOpenSQLSELECTStatementRunTime<result>,
<wherecondition>,and<orderby>
SELECT(<result>)FROM<source>
INTO<destination>
WHERE(<wherecondition>)
ORDERBY(<orderby>).
Markthe<result>,<wherecondition>and<orderby>enclosedin
parentheses.
Withthissyntax:
Youcanloadaninternaltablewiththenameofthefields<result>for
whichyouwantdatatoberetrieved.
YoucanloadanotherinternaltablewiththeWHEREcondition<where
condition>tobeappliedtotheSELECTstatement.PartoftheWHERE
conditioncanbeintheinternaltable<wherecondition>,partcanbe
hardcodedandthetwoconjoinedbythelogicaloperatorsANDandORif
required.
Youcanloadathirdinternaltablewiththenameofthefields<orderby>
forwhichyouwantthedatatobesorted.
Whenyouaresupplyingthe<result>,<wherecondition>and<orderby>
ininternaltables,youhavethefacilitytoeffectivelybuildtheseona
runtimebasis.
Youcansupplyanyoneofthese,anytwoofthese,orallofthesein
internaltables.
TheOpenSQLsystemconcatenatestheindividualrowsofeachofthese
internaltablesintoonestring.
Inyourcurrenthandsonexercise,youarefrivolouslyfillingthethree
internaltablesbyassigningliteralsanddemonstratingthefeaturesof
<result>,<wherecondition>,and<orderby>ininternaltables.Butin
Chapters10and13,thesefeaturesaredemonstratedinamoreeffective
manner.InChapter13,youarecodingaprogramsimilartotheSE16data
browser.
Thesourceprogram:
REPORTYCL_CH08_19_RSWHOR_AT_RUN_TIMELINESIZE140
NOSTANDARDPAGEHEADING.
****************************************************************
*<result>,<wherecondition>,<orderby>InInternalTables**
****************************************************************
****************************************************************
*declaredata:elementary&internaltable(simplearray)for**
*fields,WHEREcondition&orderby.**
*declarestructureKNA1.(TABLESetc.)provisiontofetchall**
*fields.**
***
*fillthefirstinternaltablewithfieldnamesforwhich**
*datatoberetrieved.**
*fillthesecondinternaltablewiththeWHEREcondition**
*fillthethirdinternaltablewithorderbyfieldnameswith**
*orderbyoption:ASCENDING/DESCENDING.**
***
*SELECT...WRITE...ENDSELECTstatementswiththeusageofthe**
*threeinternaltables**
****************************************************************
TABLES:KNA1.
DATA:FIELD(15)TYPEC,
FIELDS_TABLIKESTANDARDTABLEOFFIELD,"for<result>ininternaltable
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
26/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
CONDT(50)TYPEC,
CONDTS_TABLIKESTANDARDTABLEOFCONDT,"for<wherecondition>ininternaltable
ORDER(30)TYPEC,
ORDER_TABLIKESTANDARDTABLEOFORDER."for<orderby>ininternaltable
***************************************************
STARTOFSELECTION.
FIELD='KUNNR'.
APPENDFIELDTOFIELDS_TAB.
FIELD='NAME1'.
APPENDFIELDTOFIELDS_TAB.
*FIELD='STRAS'."decommenttheselines&tryout
*APPENDFIELDTOFIELDS_TAB.
FIELD='ORT01'.
APPENDFIELDTOFIELDS_TAB.
CONDT='NAME1LIKE''A%''OR'.
APPENDCONDTTOCONDTS_TAB.
CONDT='NAME1LIKE''C%''OR'.
APPENDCONDTTOCONDTS_TAB.
CONDT='NAME1LIKE''S%'''.
APPENDCONDTTOCONDTS_TAB.
ORDER='ORT01DESCENDING'.
APPENDORDERTOORDER_TAB.
ORDER='NAME1ASCENDING'.
APPENDORDERTOORDER_TAB.
****************************************
SELECT(FIELDS_TAB)FROMKNA1
INTOCORRESPONDINGFIELDSOFKNA1
WHERE(CONDTS_TAB)
ORDERBY(ORDER_TAB).
WRITE:/5(5)SYDBCNT,KNA1ORT01,KNA1NAME1,KNA1KUNNRUSINGNOEDITMASK,
KNA1STRAS.
ENDSELECT.
TheoutputwillappearlikeFigure824.
Figure824.Program:
YCL_CH08_19_RSWHOR_AT_RUN_TIMEOutput
Ifyouscrolltotheright,thefieldSTRASwillappearblank,becauseyou
arenotretrievingdataforit.Decommentthelinestoappendarowfor
thefieldSTRAS.Executingtheprogramafterdecommentingthelines
willmaketheoutputforfieldSTRASappear.
Similarly,aSELECTstatementwithaggregatefunctionscanhavethe
<groupbyfields>and<havingcondition>enteredinaninternaltable
andspecified(i.e.,runtime<groupbyfields>and<havingcondition>).
BYPASSINGBUFFER,CLIENTSPECIFIED,CURSORS
BYPASSINGBUFFER
Tocircumventthebuffer,fetchdatadirectlyfromthedatabasetableor
view,oryoucanusetheBYPASSINGBUFFERphraseintheOpenSQL
SELECTstatement:
SELECT...FROM<source>
BYPASSINGBUFFER..
CLIENTSPECIFIED
ItwasemphasizedearlierthatOPENSQLbydefaultretrievesonlydata
belongingtotheusersloggedinclient.Ifyouwanttoretrievedataother
thantheonebelongingtotheloggedinclient,youcanusethephrase
CLIENTSPECIFIEDintheOpenSQLSELECTstatement:
SELECT...FROM<source>
CLIENTSPECIFIED..
Bydefault,theOpenSQLSELECTstatementdoesnotallowtheclient
codefieldMANDTintheWHEREcondition.IfthephraseCLIENT
SPECIFIEDisaddedintheSELECTstatement,thefieldMANDTis
allowedintheWHEREcondition.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
27/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
Executethefollowingcodeandseetheresult:
TABLES:TCURT.
STARTOFSELECTION.
SELECT*FROMTCURTCLIENTSPECIFIEDINTOTCURT
WHERE(MANDT='810'ORMANDT='811')ANDSPRAS=SYLANGU.
WRITE:/5(4)SYDBCNT,TCURTMANDT,TCURTLTEXT.
ENDSELECT.
CURSORS
TodisassociatetheINTO<destination>fromtheOpenSQLSELECT
statement,youcanusecursors.YoucreateacursorwiththeOPEN
CURSOR<cursorname>FORSELECTSubsequently,youretrieveone
rowatatimefromthecursorintoastructurewithFETCHNEXT
CURSOR<cursorname>INTO<destination>.YouchecktheSYSUBRC
value.Ifthisisnotzero,therearenorowstobefetched.Youclosethe
cursorwithCLOSECURSOR<cursorname>.
PerformanceNotes
ReadupthePerformanceNotesofthePDFdocument:ABAP
Programming(BCABA).
ABriefonABAPDebugger
Aprogramdebuggerispartofanydevelopmentalplatform.When
programsdonotexecuteasperspecifications,errorsorbugshavetobe
locatedandidentified.Theidentifiedbugshavetobefixed.The
debuggershelpinlocatingandidentifyingthebugs.Theprogrambugs
relatetoprogramflowandvariablesnotassumingvaluesasplanned.So
thedebuggersmusthavethefacilitytotraceprogramflowand
interrogatevariablevaluesatdifferentstagesofprogramexecution,
evenatthelevelofsinglestatementexecution.
BreakPoints,WatchPoints,andExecutingProgramsinDebugging
Mode
TheABAPdebuggerprovidesforbreakpointsandwatchpointsduring
programexecution.Programhaltsoccurbecauseofthebreakpoints
and/orwatchpoints.AbreakpointcanbesetonanyexecutableABAP
statement(dynamicbreakpoints).Abreakpointcanalsobesetwitha
specialABAPstatement:BREAKPOINT(staticbreakpoints).Whenthe
programexecutesandreachesthestatementwhereabreakpointhas
beensetorreachesthespecialABAPstatementBREAKPOINT,a
programhaltoccurs.Thewatchpoints,likethebreakpoints,generate
haltsinprogramexecution.Thewatchpointhaltsaredeterminedby
valuesofwatchpointvariables.Thewatchpointsaresetbyassociatinga
watchpointwithavariableandspecifyingthevalue/rangeofawatch
pointvariable.Whenawatchpointvariableassumesavalue/rangeset
forthewatchpointvariable,ahaltoccursintheprogramexecution.
Whenaprogramhaltoccurs,generatedbyabreakpointorawatchpoint,
theABAPdebuggerpopupsadialogbox.Thisdialogboxwillbecalledthe
debuggerdialogbox.TheABAPdebuggerdialogboxisafullscreen
dialogbox.Inthedebuggerdialogbox,thedevelopercaninterrogate
dataobjectvalues,changedataobjectvalues,setfurtherbreakpoints,
resetexistingbreakpoints,viewmemoryallocationofdataobjects
includingtheinternaltables,andsetandresetwatchpoints,etc.
Apartfromthebreakpointsandwatchpointsgeneratingprogramhalts
andpoppingupthedebuggerdialogbox,youcanexecuteanABAP
programinadebuggingmodeinsteadofthenormalmode.
Dynamicbreakpointscanbesetandresetbeforethecommencementof
programexecutionandalsoduringprogramexecutionduringthehalts.
Watchpointscannotbesetandresetbeforethecommencementof
programexecution.Watchpointscanbesetandresetonlyduring
programhalts(i.e.,whendebugging,thedialogboxpopsup).
DebuggerTypes
IntheABAPworkbench,twodebuggertypesareavailable:theclassical
debuggerandthenewdebugger.Youcansetwhichdebuggertypeyou
wanttouseeitherfromtheABAPeditoropeningscreenortheABAP
programeditorscreen.Themenupathtosetthedebugger:Utilities
Settings.Inthesettingsdialogbox,ensurethatyouhaveselectedthe
ABAPEditortabandtheDebuggingtab.Thescreenforsettingthe
debuggerisshowninFigure825.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
28/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
Figure825.SelectABAPDebugger
Thenewdebuggerisanadvancedversionoftheolderclassicaldebugger.
Oneofthebasicandobviousdifferencesbetweentheclassicaldebugger
andthenewdebuggeristheappearanceofadebuggerdialogboxduring
programhalts.Withthenewdebugger,thedebuggerdialogboxappears
inanewexternalsession(extraexternalsession)whereaswiththe
classicaldebugger,thedebuggerdialogboxappearingduringprogram
executionhaltisinthesameexternalsessioninwhichtheprogramis
beingexecutedanddebugged.Apartfromthis,thereareahostofother
differencesbetweenthenewdebuggerandtheclassicaldebugger.The
newdebuggeristosuitableforuseinadvancedprogramminginvolving
manylevelsofprocedureandmethodcalls.
ThisbriefonanABAPdebuggerisconfinedtocoverageofonlythe
classicaldebugger.
BreakPointTypes
Therearetwotypesofbreakpoints:staticanddynamic.
ThestaticbreakpointscanbesetwiththespecialABAPstatement:
BREAKPOINT.Whentheprogramexecutionreachesthisstatement,the
debuggerdialogpopsup,enablingthedevelopertointerrogatedata
objectvalues,setnewdynamicbreakpoints,resetexistingdynamic
breakpoints,setwatchpoints,resetexistingwatchpoints,andcontrol
subsequentprogramhalts,etc.Thestaticbreakpointstatementsshould
bedeletedorcommentedbeforetheprogramisreleasedtotheenduser.
Therearetwotypesofdynamicbreakpoints:internalandexternal.If
youwantprogramhaltstooccurinexternalprocedureslikeexternal
subroutines,functionmodules,andmethodsofglobalclassesbeing
calledbyyourmainprogram,yousetexternalbreakpointsinthe
externalsubroutines,functionmodules,andmethodsofglobalclasses.
Theexternalbreakpointsexpireorgetresetafteratimeperiod(time
out)setbythebasisadministrator.
Theinternalbreakpointsaresetinthemainprogramyouaretesting.
Theinternalbreakpointsgetresetwhentheuserlogsoff.Theinternal
breakpointscanbesetonlyforactivatedprograms.
Thedynamicbreakpointscanbesetbypositioningthecursorona
programexecutablelineandclickingontheinternal/externalbreak
pointbuttonontheapplicationtoolbar.
ThestaticbreakpointsarerarelyusedinABAPprograms.Theyareused
inenvironmentswherethereisnofacilityfordynamicbreakpoints
like,forexample,theSmartForms(notcoveredinthisbook).Inthe
presentcoverageanddemonstrations,youwillonlyusedynamicbreak
points.Sothetermsdynamicbreakpointandbreakpointare
synonymousinthepresentdiscussion.
ExecuteProgramsinDebuggingMode
Youcanexecuteaprogramindebuggingmodebyselectingthefollowing
menuoptionontheABAPeditoropeningscreen:Program
Execute
Debugging.YoucanalsoexecuteanABAPprogramindebugging
modefrominsidetheABAPeditorwiththemenuoption:Program
Test
Debugging.
Withthisbriefintroductionanddescriptionofbreakpointsandwatch
points,furtherdebuggingfeatureswillbeexplainedthroughhandson
exercises.
Atanygiventime,foraloggedinuser,youcanhaveamaximumof30
dynamic(internal+external)breakpointsandamaximumof10watch
points.
HandsOnExerciseIABAPDebugger
LettheABAPsourceprogramYCL_CH05_05_CUST_:LIST04of
Chapter5bedebugged.Adynamic(internal)breakpointissetonthe
statement:FLAG='X'asshowninFigure826.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
29/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
Figure826.ProgramYCL_CH05_CUST_:LIST04SetInternal
BreakPoint
Inthisprogram,youlistedthecustomerdatawithanonstandardheader
andfooter.YououtputonelineoffooterasContinuedonXX.Thefooter
shouldnotappearonlastpageofthelist.Thefooterwasappearingonthe
lastpageiftherowsoutputwereamultipleoflinesoutputinthelistbody.
Asolutiontothisproblemwasproposed,whichwasbasedonthe
flow/sequenceofexecutionofprogramlines.Itwasmaintainedthatthe
eventENDOFPAGEforthelastpagewastriggeredafterexecutionof
programlinesfollowingtheENDSELECTstatement.Youcanverifythis
programflowusingthedebugger.
AsshowninFigure826,abreakpointissetonthestatementFLAG=
'X'followingthestatementENDSELECT.Withadefaultcolorsetting,an
ABAPprogramstatementwithabreakpointsetappearsinayellow
background.Whentheprogramisexecuted,thebreakpointonthe
statementFLAG='X'willtriggerahalt,andthedebuggerdialogbox
willpopupasshowninFigure827.
Figure827.DebuggerDialogBox,Program
YCL_CH05_05_CUST_:LIST04
TheexplanationofthetextboxesorlegendsinFigure827willbe
elaborateduponfollowingasequencefromlefttorightandtoptobottom.
TheexplanationofthelegendsinFigure827follows.
ButtonstoControlFurtherHalts
WiththefourbuttonsmarkedasButtonsControlFurtherProgram
Halts,youcancontrolthehaltsastheprogramexecutesfurtherfromthe
currenthalt.ThefourbuttonswiththeirlegendsareshowninFigure8
28.
Figure828.DebuggerDialogBox:ButtonsforControlFurther
ProgramHalts
TheleftmostbuttonwiththelegendSingleStep(F5)enablesyouto
executetheprogramstatementbystatement(i.e.,haltwilloccuroneach
statement).Ifaprocedure(externalsubroutineorfunctionmoduleor
method)iscalled,thehaltsoccurateverystatementofthecalled
procedureaswell.Thisbuttonshouldbeusedasthelastresort,asinthe
extremecasewhenyouwanttodebugeverystatement.
ThesecondbuttonfromtheleftwiththelegendExecute(F6)also
enablesyoutoexecutetheprogramstatementbystatementbutdiffers
fromtheexecutionwhenusingthefirstbutton.Aprocedurecall(external
subroutineorfunctionmoduleormethod)isconsideredasingle
statement.Iftherearenobreakpointsorwatchpointsinthecalled
procedure,then,whenyouclickonthisbuttonwhenahalthasoccurred
onastatementcallingtheprocedure,thenexthaltoccursonthe
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
30/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
statementfollowingthestatementcallingtheprocedure.
Ifyourcurrenthaltisinsideaprocedure(externalsubroutineorfunction
moduleormethod),therearenofurtherbreakpointsorwatchpointsin
thisprocedure,andclickingonthethirdbuttonfromtheleftwiththe
legendReturn(F7)willtriggerthenexthaltatastatementfollowingthe
statementcallingtheprocedure.ThisisshowngraphicallyinFigure8
29.
Figure829.OperationofControlFurtherProgramHaltsButton:
Return(F7)
ClickingthebuttonontheextremerightwiththelegendRun(ToCursor)
(F8)willexecutetheprogramandtriggerprogramhaltsbasedonlyon
breakpointsandwatchpointsencountered.
ButtontoCreateWatchPoint
Clickingonthisbuttonwillpopupthewatchpointcreationdialogbox.In
thewatchpointcreationdialogbox,youcanspecifythewatchpointdata
object(variable)andthevalue/rangeofwatchpointvariable.Thewatch
pointcreationisdemonstratedinthesubsequenthandsonexercise.
ButtonsDisplayField(Contents)andTable(InternalTable
Contents)
Thefirstofthetwobuttonsisusedtodisplayandchangeelementarydata
objectcontents.Thesecondofthetwobuttonsisusedtodisplayand
changeinternaltablecontents.Youcanalsoinsertandappendrowsto
internaltables.Youcandeleterowsfrominternaltables.Youcan
changecontentsofrowsofinternaltables.Thedebuggerdialogbox
showinginternaltablecontentsiscoveredinthesubsequenthandson
exercise.
Toviewstructurecontents,selectthefollowingmenupathinthe
debuggerdialogbox:Goto
Displaydataobject
structurefield.
Thesystemwillpromptforstructurename.Whenyouenterthestructure
name,thestructureisdisplayedfieldwise,eachfieldinonerow.
Structurecontentscannotbechangeddirectly.Tochangestructuredata,
youhavetoaccessindividualfieldsofthestructure.Ifthestructure
containsonlyelementarytypes:C,D,N,andT,thestructurecanbe
displayedasonefield.
InFigure827,thefieldFLAGisenteredanditsvalueisdisplayed.You
canenteranyelementarydataobjectorasystemfieldanditsvaluewill
bedisplayed.Bydefault,foursystemfieldsvaluesaredisplayedatthe
bottomofthedebuggerdialogbox.
ButtonsBreakPointsandWatchPointsOverview
Thesetwobuttonspopupthebreakpointsandwatchpointsoverview
dialogboxes.
ProgramPane,ProgramVScroll,andHScrollButtons
Thesourceprogrampanedisplaysthesourceprogramlines.Thereare
fourbuttonstoscrollhorizontallyleftandright,andtoscrollverticallyup
anddown.
BreakPointStatementsandCurrentHaltstatement
Intheprogrampaneofthedebuggerdialogbox,anABAPstatementwith
abreakpointsetappearswiththeicon
ontheleftsideandanABAP
statementwherethecurrenthaltoccurredappearswiththeicon
ontheleftside.AnABAPstatementwithabreakpointandthecurrent
haltappearswithbothoftheseiconsontheleftsidelikethis:
Youcanresetabreakpointonastatementbydoubleclickingonthe
statement.Similarly,youcansetabreakpointbydoubleclickingonthe
statement.
ChangeFieldContentsButton
Atthebottomright,thereisabutton
toconfirmthechangeof
contentsofafield.
FollowingtheProgramFlow
InFigure827,theprogramhashaltedatthestatementFLAG='X'.The
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
31/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
valueofthevariableFLAGisblankatthisstage.
Inthesourceprogrampane,scrollupandsetabreakpointatthe
statementIFFLAG=''followingtheeventstatement:ENDOF
PAGE.Abreakpointcanbesetbypositioningthecursoronthe
statementandselectingthemenuoption:BreakPoints
Create/Delete.Abreakpointonastatementcanbesetorresetby
doubleclickingonthestatement.
Next,clickontheRun(functionkeyF8)button.Thedebuggerdialog
boxwillappearforthebreakpointsetatthestatementIFFLAG=''.
ThevalueofthevariableFLAGisnowX.ThisisshowninFigure830.
Figure830.BreakPointhaltatstatement:IFFLAG=''
TheprogramflowisaspertheclaimsmadeinChapter5,andthe
programlinesfollowingtheENDSELECTstatementgetexecutedbefore
theENDOFPAGEeventgetstriggeredforthelastpageofthelist.
Thenexthandsonexercisewilldemonstratethedisplayofinternaltable
contentandwatchpoints.
HandsonExerciseIIABAPDebugger
LettheABAPsourceprogramYCL_CH06_ITAB05ofChapter6be
debugged.Inthisprogram,youlistedcustomerwisesalessummaryofa
specificcompanycode.YouusedtheinternaltableCOLLECTstatement
togeneratethesalessummary.Adynamic(internal)breakpointisseton
thestatement:SORTSALES_TABBYKUNNR.Executetheprogramwith
companycode3000.Whentheprogramisexecutedwiththisdynamic
breakpoint,theprogramcomestoahaltandpopsupthedebuggerdialog
boxasshowninFigure831.
Figure831.InternalBreakPointinProgram
YCL_CH06_ITAB05
IfyouclickontheTablebutton,thedebuggerdialogboxwillpromptfor
theinternaltablename.EntertheinternaltablenameasSALES_TAB.
YoucanviewthecontentsoftheinternaltableSALES_TABasshownin
Figure832.
Figure832.ProgramYCL_CH06_ITAB05:InternalTable
SALES_TABContents
AsshowninFigure832,youcanchangerowcontents,insertrows,
appendrows,anddeleterowsintheinternaltablewithbuttonsprovided
atthebottomofthedebuggerdialogbox.
Ifyouwantthememoryallocationinformationfortheinternaltables,
selectthemenuoption:Settings
MemoryDisplayOn/Off.Thismenu
optiontogglesforappearanceordisappearanceofthememoryallocation
ofdataobjects.ThememoryallocationsappearatthebottomoftheABAP
debuggerscreen.Figure833showsthememoryallocationforthe
internaltableSALES_TAB.
Figure833.ProgramYCL_CH06_ITAB05MemoryAllocation
ofInternalTableSALES_TAB
Letawatchpointbecreated.Whenyouclickthebuttontodisplay
internaltablecontents,theapplicationtoolbarchangesandthebuttonto
createwatchpointsdisappears.Sotocreateawatchpoint,makethe
followingmenuselection:BreakPoints
Createwatchpoint.When
youmakethismenuselection,thefollowingdialogappears:
Figure834.DialogBoxtoCreateaWatchPoint
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
32/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
Inthewatchpointdialogbox,youenterthewatchpointfieldnameor
watchpointvariableforwhichyouwanttoestablishawatchpointinthe
fieldFieldname.Youenterthewatchpointrelationoperatorinthefield
RelationalOperator.Therelationaloperatorsacceptedare<,<=,=,
<>,>=,and>.Themnemonicequivalentsofthesearithmetical
relationaloperatorsarealsoaccepted.Aselectionlist(F4)isavailable.
Youcancomparethewatchpointvariableeitherwithanothervariableor
aliteral.Ifyouarecomparingthewatchpointvariablewithanother
variable,(comparisonvariable),enablethecheckboxwiththelegend
ComparisonfieldIfyouarecomparingthewatchpointvariablewitha
literal,thenensurethischeckboxisdisabled.Enterthecomparison
variableorliteralinthefieldComp.field/value.
LetawatchpointbecreatedforthevariableSALES_STRUNETWR.So
enterthisvariableasthewatchpointvariable.Selecttherelational
operatorasGE(>=).Letthewatchpointvariablebecomparedwitha
literal.Enterthevalue4000000(fourmillion)inthefieldComp.field
value.Whatyoudesireisthatwheneverthewatchpointvariable
SALES_STRUNETWRisgreaterthanorequaltofourmillion,ahalt
mustoccur.Figure835showsthewatchpointdialogboxwiththeentered
values.
Figure835.WatchPointDialogBoxwithEnteredValues
Clickonthecontinuebuttonofthewatchpointcreationdialogbox.A
watchpointcreationmessagewillappearonthestatusbar.Clickonthe
Run(ToCursor)(F8)
button.Ahaltwilloccureverytimethe
valueofthewatchpointvariable>=4,000,000.Inthisprogram,thefirst
timethewatchpointhaltoccursforthecustomercodeSALES_STRU
KUNNR=0000300700.ThevalueofsystemfieldSYTABIXis46.This
isshowninFigure836.
Figure836.WatchPointHaltforSALES_STRUKUNNR=
0000300700
Inalikemanner,fivemorehaltswilloccurwhenthewatchpoint
variableSALES_STRUNETWR>=4000000.Thecorrespondingvalues
ofthefieldSALES_STRUKUNNRforthefivehaltsare0000300701,
0000300703,0000300704,0000300705,and0000300719.The
correspondingvaluesofthesystemfieldSYTABIXforthefivehaltsare
47,48,50,51,and60.
Thiswasademonstrationofviewinganinternaltablecontents,viewing
memoryallocationofaninternaltable,andthesettingupofawatch
point.
ConclusionABAPDebugger
ThisbriefontheABAPdebuggerintroducedyoutothedebuggertypes
andsettingadebuggertype.Itintroducedyoutothebreakpoints,types
ofbreakpoints,andwatchpoints.YoulearnedhowtoexecuteanABAP
programindebuggingmode.
Theelementsofthedebuggerdialogboxanditsbasicoperationswere
demonstratedinthefirstofthehandsonexercises.Thesecondhandson
exercisefurtherdemonstratedtheoperationsofthedebuggerdialogbox.
TheABAPdebuggerwasdemonstratedwithapparentlybugfree
programs.Theobjectivewastoexposeyoutothebasicfeaturesofan
ABAPdebuggingenvironmentincludingtheoperationofthedebugger
dialogbox.
Exploreandtryoutotherfeaturesandoptionsofthedebugger.Trytouse
thedebuggerinatleastonehandsonexerciseofanupcomingchapter.
Useadebuggerinyourownhandsonexercises.Tryoutthenew
debuggeraswell.
Conclusion
TheOpenSQLSELECTstatementwillbeutilizedinalltheupcoming
chapters.
ThethreesomefeaturesofOpenSQLruntimespecifications,FIELD
SYMBOLS,andtheruntimecreationofdataobjectsiscarriedforward
anddevelopedinChapters10and13intoadvancedsophisticated
applications.
YouwerealsointroducedinthischaptertotheABAPdebugger.
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
33/34
1/5/2016
Chapter8:OpenSQLDataRetrievalSAPABAP:HandsOnTestProjectswithBusinessScenarios
PREV
Chapter 7: Modularization
NEXT
Chapter 9: SELECTION-SCREENS
Recommended / Queue / Recent / Topics / Tutorials / Settings / Blog / Feedback / Sign Out
2016 Safari.
Terms of Service / Privacy Policy
https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch08.xhtml
34/34