Вы находитесь на странице: 1из 18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

SAPSystemSetupTrainingCourse
RevealsHowToSetupAFreeSAPDeveloperSystem.
LearnSAP&PracticeForCertification.DeveloperTipsIncluded:

HowToModifyDataInASAPDatabaseTable
UsingABAP
January13,2014, byPete, Commentsareoff

Authorisations
WhenwritingprogramsusingopenSQL,onehastobearinmindthe
conceptsofauthorisationinanSAPsystem.AnSAPsystemhasitsown
securitytoolstoensurethatuserscanonlyaccessdatawhichtheyare
authorisedtosee.Thisincludesindividualfieldsaswellasindividual
records.Thewayauthorisationsaresetupcanalsolimithowdatais
used,whetherausercanonlydisplaydataorwhethertheycanmodifyit.
Alltherulespertainingtothisarestoredasauthorisationobjects.These
willnotbeexaminedingreatdetailhere,butordinarilyusersare
assignedtheirownauthorisationprofile(orcompositeprofile)against
theiruserrecord,whichforinformationalpurposesismanagedthrough
transactioncodeSU01.
Thisprofilethengivestheuserthecorrectrightswithintheprogramto
thencarryouttheirjobandSAPdeliversmanypredetermineduser
profileswiththebasesystem.Thesystemadministratorscanthenuse
andenhancethesetobeappliedtousers.Onceauserhasoneofthese
profiles,thesystemwilltellthemwhetherornottheycanexecutea
transactionwhentheytrytodothis.Forexample,transactionSE38,the
http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

1/18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

ABAPeditor,couldbetweakedsothatwhilesomeusersmaybeableto
accessit,perhapstheycanonlydosoindisplaymode,orperhapsthey
candisplayanddebugthecode,butnotchangeitthemselves.
Wherespecificauthorisationshavenotbeenimplemented,programscan
bemadetocarryoutanauthoritycheck,usingthestatement
AUTHORITYCHECK.Thismustbeusedifaprogramortransactionis
notsufficientlyprotectedbythestandardauthorisationprofilesalready
setupinthesystem.
While,thiswillnotbeexaminedingreatdetailhere(thetopicishugein
itself),itisimportanttobearauthorisationsinmindwhenworkingin
SAP.

Fundamentals
Sofar,readingdatafromdatabasetableshasbeenlookedat,now
modifyinganddeletingthisdatawillbeexamined.Therearesome
importantconceptstokeepinmindhere,forexample,thearchitecture
ofthesystem.Ifonehasathreetierarchitecture(withapresentation
layer,anapplicationserverandanunderlyingdatabase),youmustbear
inmindthattheremaybeaverylargenumberofusersaccessingthedata
atanyonetime.
Itisimportanttoensurethatprogramscreateddonotcauseany
problemsintherestofthesystemandthatthemostrecentversionof
thedataheldonthedatabaseisaccessedwhenaprogramruns.If
recordsareconstantlybeingupdated,programsmustbeabletoreadand
workwithdatawhichiscurrentinthesystem.Fortunately,mostofthis
workisdoneautomaticallybytheSAPsystem,andonedoesnthaveto
worrytoomuchabouttheunderlyingtechnologiesrelatedtohowdatais
lockedandsoon.
OneofthekeytoolswhichcanbeusedisOpenSQL.Thisactsasan
interfacebetweentheprogramscreatedandthedatabase.ByusingOpen
SQL,onecanreadandmodifydata,andalsobufferdataonthe
applicationserver,whichreducesthenumberofdatabaseaccessesthe
systemhastoperform.Itisthedatabaseinterfacewhichisalso
responsibleforsynchronisingthebufferswiththedatabasetablesat
predeterminedintervals.
Whenoneiscreatingprogramsitisimportanttokeepinmindthatif
dataisbuffered,andthisbuffereddataissubsequentlyread,itmaynot
alwaysbeuptodate.So,whentablesarecreated,theymustbecreatedin
http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

2/18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

suchawaythatthesystemistoldthatbufferingcanorcannotbeused,or
thatitcanonlybeusedincertainsituations.Whentheexampletables
werecreatedearlier,thesystemwastoldnottousebuffering.Usingthis
settingmeansthateverytimedataisreadfromatable,itwillalwaysuse
themostuptodaterecords.
Bufferingcanbeusefulfortableswhichholdmasterdataand
configurationsettings,becausethiskindofdatadoesnotgetupdated
regularly.Whenoneisworkingwithtransactionaldatahowever,one
wantsthisdatatobeasuptodateaspossible.Iftransactionaldatais
beingusedinacontextwheretablesareusingbuffering,itisimportant
toensurethatprogramsrelatedtothiscantakethisintoaccount,and
makesurethatthebufferisupdatedwithnewdatawhenthisisneeded.
WhenoneusesOpenSQLstatementsinaprogram,tablescanonlybe
accessedthroughtheABAPdictionary.Thisactsasaninterface,onedoes
notaccessthetablesdirectlythroughprograms.Thisisnotaproblem
however,aswhenoneusesOpenSQLstatements,itworksjustthesame
asifonewasaccessingthedatabasedirectly.OpenSQLmanagesits
interfacewiththedatabasebyitself,withouttheneedfortheusertodo
anythinghere.Statementscanbecodedjustasthoughtheyhaddirect
accesstothetables,thoughwiththeunderlyingknowledgethatbyusing
OpenSQL,thedataisinfactbeingaccessedthroughtheABAPdictionary
withabuiltinlevelofsafetytoensuretheABAPcodedoesnothavea
directeffectontheSAPdatabasesystemitself.

DatabaseLockObjects
Now,lockingconceptswillbeconsidered.Thisreferstolockingdatain
databasetablesandtherearetwobasictypesoflockingwhichmustbe
keptinmind.Firstofall,databaselocks.Theselockdatainaphysical
database.Whenarecordisupdated,alockissetonthis,thenwhenitis
updatedthelockisreleased.Itistheretoensurethat,onceset,thedata
canonlybeaccessedandupdatedbythoseauthorisedtodoso.When
released,itcanbeaccessedmorewidely.
Theselocks,though,arenotsufficientinanSAPsystem,andare
generallyonlyusedwhenarecordisbeingmodifiedinasinglestep
dialogueprocess.Thisprocessreferstoanytimethatthedataina
databasecanbeupdatedinasinglestep,onasinglescreen.Inthiscase,
thedatacanbelocked,updatedandreleasedveryquickly.
AsyouworkmorewithSAP,theinsufficiencyofdatabaselockswill
becomeclearer,becausetransactionsinanSAPsystemoftenoccurover
http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

3/18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

multiplesteps.If,forexample,anemployeerecordisaddedtothe
system,onemayhavetofillinmanyscreensofdata.Theuserinthiscase
willonlywanttherecordtobeaddedtothesystemattheendofthelast
screen,onceallofthedatainallofthescreenshasbeeninput.Ifjustthe
firstscreensdatawassavedintothedatabase,thentheseconds,andso
on,onebyone,iftheuserweretoquithalfwaythroughtheprocess,an
invalidandunfinishedrecordwouldbeinthedatabase.
Thisdemonstratesthehazardofusingdatabaselockswithmultistep
dialogueprocesses.Fortheseinstances,SAPhasintroducedanewkind
oflock,independentofthedatabasesystem.Thesearecalledlock
objects,andallowdatarecordstobelockedinmultipledatabasetables
forthewholedurationoftheSAPtransaction,providedthattheseare
linkedintheABAPdictionarybyforeignkeyrelationships.
SAPlockobjectsformthebasisofthelockconcept,andarefully
independentofdatabaselocks.Alockobjectallowsonetolockarecord
formultipletablesfortheentiredurationofanSAPtransaction.Forthis
towork,thetablesmustbelinkedtogetherusingforeignkeys.TheABAP
dictionaryisusedtocreatelockobjects,whichcontainthetablesandkey
fieldswhichmakeupasharedlock.
Whenthelockobjectiscreated,thesystemautomaticallycreatestwo
functionmodules,whichwillbediscussedlater.Thesefunctionmodules
aresimplymodularisedABAPprogramsthatcanbecalledfromother
programs.Thefirstofthesehastheactionofsettingalock,andthe
secondreleasesthislock.Itistheprogrammersresponsibilitytoensure
thatthesefunctionmodulesarecalledatthecorrectplaceinthe
program.Whenalockisset,alockrecordiscreatedinthecentrallock
tablefortheentireSAPsystem.Allprogramsmustadheretousingthe
SAPlockconcepttoensurethattheyset,deleteandquerythelocktable
thatstoresthelockrecordsfortherelevantentries.
Lockobjectswillnotbediscussedmuchfurther,howeversubsequent
programscreated,tablesaccessedandsoonherewillbedoneonthe
assumptionthattheyarenottobeusedoutsideofonesownsystem.

UsingOpenSQLStatements
Now,someoftheOpenSQLstatementswhichcanbeusedinprograms
willbelookedat.Asmentionedbefore,OpenSQLstatementsallowone
toindirectlyaccessandmodifydataheldintheunderlyingdatabase
tables.TheSELECTstatement,whichhasbeenusedseveraltimes
previously,isverysimilartothestandardSQLSELECTstatementused
http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

4/18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

bymanyotherprogramminglanguages.WithOpenSQL,thesekindsof
statementscanbeusedinABAPprogramsregardlessofwhatthe
underlyingdatabaseis.Thesystemcouldberunning,forexample,an
Oracledatabase,aMicrosoftSQLdatabase,oranyother,andbyusing
OpenSQLinprogramsinconjunctionwiththeABAPdictionarytocreate
andmodifydatabasetables,onecanbecertainthattheABAPcodewill
nothaveanyissuesaccessingthedataheldbythespecifictypeof
databasetheSAPsystemuses.
Whenthefirstdatabasetablewascreatedpreviously,thefieldMANDT
wasused,representingtheclientnumberandformingpartofthe
databasetablekey,highlightedbelow:

Onemaythinkthat,giventheimportanceofthisfield,itwouldhaveto
beusedinABAPprogramswhenusingOpenSQLstatements,however,it
doesnot.Almostalltableswillincludethishiddenfieldwithinthem,
andtheSAPsystemisbuiltinsuchawaythatafilterisautomatically
appliedtothisfield,basedontheclientIDbeingused.Ifoneisloggedin,
forexample,toclient100,thesystemwillautomaticallyfilterallrecords
inthedatabaseonthisclientkeyandonlyreturnthoseforclient100.
WhenOpenSQLisusedintheprogramsonecreates,thesystem
managesthisfielditself,meaningitneverhastobeincludedinany
selectionsorupdatestatementsusedinprograms.Also,thiscarriesthe
benefitofsecurityintheknowledgethatanyOpenSQLstatement
executedinaprogramwillonlyaffecttherecordsheldinthecurrent
client.

UsingOpenSQLStatements5Statements
Thereare5basicOpenSQLstatementswhichwillbeusedregularlyin
programsfromhereforward.TheseareSELECT,INSERT,UPDATE,
MODIFYandDELETE.
TheSELECTstatementhas,ofcourse,alreadybeenused.This
statementallowsonetoselectrecordsfromdatabasetableswhich
willthenbeusedinaprogram.
INSERTallowsnewrecordstobeinsertedintoadatabasetable.

http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

5/18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

UPDATEallowsrecordswhichalreadyexistinthetabletobe
modified.
MODIFYperformsasimilartasktoupdate,withslightdifferences
whichwewilldiscussshortly.
DELETE,ofcourse,allowsrecordstobedeletedfromatable.
WheneveranyofthesestatementsareusedinanABAPprogram,itis
importanttocheckwhethertheactionexecutedhasbeensuccessful.If
onetriestoinsertarecordintoadatabasetable,anditisnotinserted
correctlyoratall,itisimportanttoknow,sothattheappropriateaction
canbetakenintheprogram.Thisisdoneusingasystemfieldwhichhas
alreadybeenused:SYSUBRC.Whenastatementisexecuted
successfully,theSYSUBRCfieldwillcontainavalueof0,sothiscanbe
checkedforand,ifitappears,onecancontinuewiththeprogram.Ifitis
notsuccessful,however,thisfieldwillcontainadifferentvalue,and
dependingonthestatement,thisvaluecanhavedifferentmeanings.Itis
thereforeimportanttoknowwhatthedifferentreturncodesareforthe
differentABAPstatements,soastorecogniseproblemsandtakethe
correctcourseofactiontosolvethem.Thismaysounddifficult,butwith
practicewillbecomesecondnature.

InsertStatement
TheSELECTstatementhasalreadybeenused,sohereitwillbeskipped
fornowtofocusontheINSERTstatement.Inthisexamplethen,anew
recordwillbeinsertedintotheZEMPLOYEEStable.Firstly,type
INSERT,followedbythetablename,andthenaperiod:

Doingthis,onemustalwaystypethetablename,avariablesname
cannotbeusedinstead.Usethecheckstatement(IF)toincludeanSY
SUBRCcheck,tellingthesystemtodoifthisdoesnotequal0:

ThisisthesimplestformoftheINSERTstatement,andnotnecessarily
theonewhichisencouraged.Usingthisformisnolongerstandard
practice,thoughonemaycomeacrossitifworkingwitholderABAP
programs.
http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

6/18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

Intheabovestatement,nothingisspecifiedtobeinserted.Thisiswhere
theconceptoftheworkareaenters.Thestatementhereexpectsawork
areatoexistwhichhasbeencreatedwhenaninternaltablewasdeclared.
Thistypeofworkareaisoftenreferredtoasaheaderrecord:

Thetableaboveshowstheyellowareaasastandardtablecontaining
fourrecordsandtheirrespectivefields,theareaaboveingreyisthe
headerrecord,whichisstoredinmemoryandistheareawhichis
accessedwhenthetableisreferencedfromaprogramonlybyitstable
name.IfanINSERTstatementisexecuted,whateveriscontainedinthe
headerrecordwillbeinsertedintothetableitself.Theheaderrecord
doesnotexistinthetable,itisjustanareastoredinmemorywherea
currentrecordcanbeworkedwith,hencethetermworkarea.When
someonereferstothetableonlybyitstablename,itistheheaderrecord
whichisreferredto,andthiscanbecomeconfusing.Onethinksthatone
isreferencingthetableitself,butinfactitistheheaderrecordwhichis
beingworkedwith,arecordheldinmemorywiththesamestructureas
thetable.ABAPobjects,whichareimportantwhenonegetstoamore
advancedstageinABAP,willnotallowaheaderrecordtobereferredto,
soitisimportantnottodothis.Headerrecordswereusedcommonlyfor
thisinthepast,butasnotedpreviously,thisisnolongerthewaythings
aredone.
Toavoidconfusionwhenworkingwithinternaltablesshouldprograms
mustworkwithseparateworkareas,whichareperhapssimilarin
structuretoaheaderrecord,butnotattachedtothetable,witha
separatename.Theseareseparatestructuresfromtheinitialtable,
whicharecreatedinaprogram.

http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

7/18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

TodeclareaworkareatheDATAstatementisused.Givethisthename
wa_employees.Now,ratherthandeclaringonedatatypeforthis,
severalfieldswhichmakeupthetablewillbedeclared.Theeasiestway
todothisistousetheLIKEstatement.
Sohere,thewa_employeesworkareaisdeclaredLIKEthezemployees
table,takingonthesamestructurewithoutbecomingatableitself.This
workareawillonlystoreonerecord.Oncethisisdeclared,theINSERT
statementcanbeusedtoinserttheworkareaandtherecorditholdsinto
thetable.ThecodeherewillreadINSERTzemployeesFROM
wa_employees:

Additionally,usingthisformoftheINSERTstatementallowsyouto
specifythetablenameusingavariableinstead.Itisimportanttonote
herethatifoneisdoingthis,thevariablemustbesurroundedby
brackets.
Now,theworkareamustbefilledwithsomedata.Usethefieldnames
fromthezemployeestable.Thiscanbedonebyforwardnavigation,
doubleclickingthetablenameinthecode,orbyopeninganewsession
andusingSE11.Thefieldsofthetablecanthenbecopy&pastedintothe
ABAPeditorandtheworkareasfieldspopulatedasintheimagebelow:

Thecheckstatementcanthenbeformulatedasfollows,meaningthatif
therecordisinsertedcorrectly,thesystemwillstatethis,ifnotthenthe
SYSUBRCcodewhichwillnotequalzeroiswillbedisplayed:

http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

8/18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

Checktheprogram,save,andactivatethecode,thentestit.Theoutput
windowwilldisplay:

IfyouchecktherecordsinyourtableviatheDataBrowserscreeninthe
ABAPdictionary,anewrecordwillbevisible:

ForpracticeusetheABAPdebuggertoexecutethecodestepbystep.
First,deletetherecordfromthetableintheABAPdictionaryandputa
breakpointinthecodeatthebeginningoftherecordentrytothework
area:

Nowexecutetheprogram.Thebreakpointwillcauseprogramexecution
topauseatyourbreakpointandthedebuggerwillopen:

Firstly,usetheFieldsmodetoviewtheworkareastructure.Doubleclick
thewa_employeesaftertheDATAstatementanditwillappearinthe
Fieldnamesboxatthebottom.Atthispointtheworkareaiscompletely
empty,evidencedbythezerosintheadjacentbox.Todisplaythefull
structure,doubleclickthewa_employeesintheleftbox:

http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

9/18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

Then,executeeachlineofcodestartingfromthebreakpointusingtheF5
key,thefieldswithinthisstructureviewarefilledonebyone:

ReturntotheFieldsviewbeforeexecutingtheINSERTstatement,and
observetheSYSUBRCfieldatthebottomofthewindow.Itdisplaysa
valueof0.Ifthereareanyproblemsintheexecution,thiswillthen
change(4forawarning,8foranerror).Giventhatthiscodehasalready
beensuccessful,youalreadyknowthatitwillremain0.Oncethe
programhasbeenexecutedinthedebugger,refreshthetableintheData
Browserscreenagain,andtherecordwillbevisible.

ClearStatement
Atthispoint,theCLEARstatementwillbeintroduced.InABAP
programs,onewillnotalwayssimplyseetheprogramstartatthetop,
insertonedatarecordandcontinueon.Loopsandthelikewillbesetup,
allowing,forexample,manyrecordstobeinsertedatonce.Todothis,
variablesandstructuresarereusedrepeatedly.TheCLEARstatement
allowsafieldorvariabletobeclearedoutfortheinsertionofnewdatain
itsplace,allowingittobereused.TheCLEARstatementiscertainlyone
whichisusedcommonlyinprograms,asitallowsexistingfieldstobe
usedmultipletimes.
Inthepreviousexample,theworkareastructurewasfilledwithdatato
createanewrecordtobeinsertedintothezemployeestable,thena
http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

10/18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

validationcheckperformed.Ifonethenwantstoinsertanewrecord,the
workareacodecanthenbecopy&pastedbelowthis.However,sincethe
workareastructureisalreadyfull,theCLEARstatementmustbeusedso
thatitcanthenbefilledagainwiththenewdata.
Todothis,thenewlineofcodewouldreadCLEARwa_employees.
Ifyoujustwantedtoclearspecificfieldswithinyourstructureyoujust
needtospecifytheindividualfieldstobecleared,asintheexample
below,cleartheemployeenumberfield.Newdatacanthenbeentered
intotheworkareaagain:

Rememberthattheemployeenumberisakeyfieldforthezemployees
table,soaslongasthisisunique,duplicateinformationcouldbeentered
intotheotherfields.Ifonetriestoenterthesameemployeenumber
againthough,thesysubrcfieldwilldisplayawarningwiththenumber4.
YoucanseetheoperationoftheCLEARstatementindebugmode.The
threeimagesbelowdisplaythethreestagesofitsoperationonthefield
contentsasthecodeisexecuted:

http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

11/18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

UpdateStatement
TheUPDATEstatementallowsoneormoreexistingrecordsinatableto
bemodifiedatthesametime.Inthisexampleitwilljustbeappliedto
one,butformorethesameprinciplesgenerallyapply.
JustaswiththeINSERTstatement,aworkareaisdeclared,filledwith
thenewdatawhichisthenputintotherecordastheprogramis
executed.
DeletetherecordcreatedwiththeCLEARstatementasbefore.Here,the
recordpreviouslycreatedwiththeINSERTstatementwillbeupdated.
Copy&pastetheworkareaandthenalter,thetextstoredinthe
SURNAMEandFORENAMEfields.Thenonanewline,thesame
structureasfortheINSERTstatementisused,butthistimeusing
UPDATE:

Asthisisrunlinebylineindebugmode,youcanseetheFieldcontents
changeasitisexecuted:

http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

12/18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

OncetheUPDATEstatementhasbeenexecutedyoucanviewtheData
BrowserintheABAPDictionarytoseethattherecordhasbeenchanged
successfully:

ModifyStatement
TheMODIFYstatementcouldbesaidtobelikeacombinationofthe
INSERTandUPDATEstatements.Itcanbeusedtoeitherinsertanew
recordormodifyanexistingone.Generally,thoughtheINSERTand
UPDATEstatementsaremorewidelyusedforthesepurposes,since
theseoffergreaterclarity.UsingtheMODIFYstatementregularlyfor
thesepurposesisgenerallyconsideredbadpractice.However,timeswill
arisewhereitsuseisappropriate,forexampleofoneiswritingcode
wherearecordmustbeinsertedorupdateddependingonacertain
situation.
Unsurprisingly,theMODIFYstatementfollowssimilarsyntaxtothe
previoustwostatements,modifyingtherecordfromthedataentered
intoaworkarea.Whenthisstatementisexecuted,thekeyfieldsinvolved
willbecheckedagainstthoseinthetable.Ifarecordwiththesekeyfield
valuesalreadyexists,itwillbeupdated,ifnotthenanewrecordwillbe
created.
Inthefirstsectionofcodeintheimagebelow,sinceemployeenumberis
thekeyfield,and10000006alreadyexists,therecordforthat
employeenumberwillbeupdatedwiththenewnameinthecode.A
validationcheckisperformednext.TheCLEARstatementisthenusedso
anewentrycanbeputintotheworkarea,andthenemployee10000007
isadded.Sincethisisanew,uniquekeyfieldvalue,anewrecordwillbe
inserted,andanothervalidationcheckexecuted:

http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

13/18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

Whenthisisexecuted,andthedatathenviewedintheDataBrowser,
employeenumber10000006willhavebeenupdatedwiththenewname,
PeterNorthmore,andanewrecordwillhavebeencreatedfornumber
10000007,SusanSouthmore:

DeleteStatement
ThelaststatementtobelookedatinthissectionistheDELETE
statement.Onemustbecarefulusingthis,becauseifusedincorrectly,
thereisthepossibilityofwipingtheentirecontentsofthetable,
however,aslongasitisusedcorrectly,thereshouldbenoproblemof
thissort.
UnlikethepreviousSQLstatements,theDELETEstatementdoesnot
takeintoaccountmostfields,onlytheprimarykeyfield.Whenyouwant
todeletearecordfromatable,thesystemonlyneedstobetoldwhatthe
primarykeyfieldvalueforthatrecordis.
Inthisexample,thelastrecordcreated,fortheemployeeSusan
Southmorewillbedeleted.Forthezemployeestable,therearetwokey
fields,theclientfieldandtheemployeenumber.Theclientfieldisdealt
withautomaticallybythesystem,andthisneverhastobeincludedin
programs,sotheimportantfieldhereistheemployeenumberfield.The
syntaxtodeletethelastrecordcreatedintheprevioussectionwouldbe
this:

http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

14/18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

TheFROMadditioninthelastlineensuresonlytherecordreferredtoby
itskeyfieldintheworkareawillbedeleted.Again,avalidationcheckis
performedtoensuretherecordisdeletedsuccessfully.Whenthisisrun
indebugmodeyoucanseethefieldswhicharefilledwiththecreationof
therecordareclearedastheCLEARstatementexecutes.
AftertheemployeenumberisfilledagaintheDELETEstatementis
executed.Thecodesoutputwindowwillindicatethesuccessofthe
deletionandtherecordwillnolongerappearintheBrowserviewofthe
table:

http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

15/18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

Therecordisnowgonefromthetable.
ThereisanotherformoftheDELETEstatementwhichcanbeused.You
arenotjustrestrictedtousingthetablekeytodeleterecords,logiccan
alsobeused.So,ratherthanusingtheworkareatospecifyakeyfield,
andusingtheFROMadditiontotheDELETEstatement,onecanusethe
WHEREadditiontotelltheprogramtodeleteallrecordswhereacertain
fieldmatchesacertainvalue,meaningthatifonehasseveralrecords
whichmatchthisvalue,allofthemwillbedeleted.
Thenextexamplewilldemonstratethis.Allrecordswiththesurname
Brownwillbedeleted.Tobeabletodemonstratethis,createasecond
recordcontainingasurnameofBrown,savethisandviewthedata:

LEARN SAP $19!

Save 80% on allcourses ...Click for Discount Links

MORE >>

ThecodeforthenewDELETEstatementshouldthenlooklikethis.Note
theadditionalFROMwhichmustbeusedinthisinstance:

http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

16/18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

Whenthiscodeisexecuted,bothrecordscontainingaSurnameofBrown
willbedeleted.

LEARN SAP $19!

Save 80% on allcourses ...Click for Discount Links

MORE >>

Notethat,ifoneusesthefollowingpieceofcode,withoutspecifyingthe
logicaddition,alloftherecordswillinfactbedeleted:

SAPABAP
abap

ABAPDictionary

SAP

AbouttheAuthor:Pete
PetehasbeenworkingwithSAPtechnologies
forover10years.HestartedoutasanABAP
consultantandthenmovedontoBWwherehe
hasworkedmanydifferentclientscoveringa
widevarietyofindustries."Iloveintroducing
SAPtechnology(especiallyBI)tonewclients
andshowingthemhowtheycangofromzeroto
herowithintheirbusinessinsuperfasttime".
Contactmeontwitter@PeterMoxon

http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

17/18

23/09/2016

HowToModifyDataInASAPDatabaseTableUsingABAP|SAPTrainingHQ

CopyrightSAPPROUKLimited
Thiswebsiteisnotaffiliatedwith,
sponsoredby,orapprovedbySAPAG

ThissiteusescookiesMoreinfo

Developer
Courses

IntroCourses

Noproblem

Reporting

Books

LearnSAPOnline

LearnSAPBWBEx

Beginner'sGuideTo

SAPABAPTraining

BeginnerTraining

Analyzer2013

SAPABAP

ForBeginners

Course

AcademyTraining

Programming

SAPABAPObjects

SAPFinancial

SAPBExAnalyzer

OnlineTraining

AccountingOverview

AndQueryDesigner

Course

TrainingCourse

LEARN SAP $19!

Save 80% on allcourses ...Click for Discount Links

http://www.saptraininghq.com/howtomodifydatainasapdatabasetableusingabap/

MORE >>

18/18

Вам также может понравиться