Code examples
SAP code you can copy, run and actually understand
Every example starts from a real requirement, shows how the pieces connect, then builds it step by step. Hover, tab to or tap any part of the code to see what it does and why it is there. Each step has a copy button.
All examples are original teaching code using illustrative Z-object names. Activate them in a sandbox or trial system first and check the syntax against your release.
67 examples
Want just the code? Copy or download everything on one page
- Modern ABAPBeginner
ABAP first steps: variables, IF, CASE and loops in a runnable class
Write your first ABAP program as a class you can run with F9: declare variables, decide with IF and CASE, repeat with DO and WHILE, and print the result.
3 steps · 7 explained parts - Modern ABAPBeginner
Dates in ABAP: add days, find the month end and age an invoice into buckets
Learn how ABAP stores a date, add and subtract days, find the last day of a month, and sort invoices into overdue buckets by their age.
4 steps · 5 explained parts - Modern ABAPBeginner
Your first SAP data read: look up a customer in table KNA1
For someone who has never written ABAP: find a customer in the customer master table KNA1, print the name and city, handle the case that the customer does not exist, and list the first five customers.
4 steps · 6 explained parts - Modern ABAPBeginner
Your first short dump: cause, read and fix GETWA_NOT_ASSIGNED
Make a field symbol dump on purpose, read the dump to find the line, understand the cause with the debugger and fix the program with a check.
3 steps · 4 explained parts - Modern ABAPBeginner
ABAP SQL: create a table, then insert, read, update and delete rows
Define a small database table in ADT, then change its data with INSERT, SELECT, UPDATE and DELETE and check SY-SUBRC and SY-DBCNT after each statement.
4 steps · 7 explained parts - Modern ABAPBeginner
Material master: join MARA and MAKT to list materials with their description
Combine the material table MARA with the text table MAKT in one SELECT, choose the description in the user's language and print five finished products.
4 steps · 4 explained parts - Modern ABAPIntermediate
Sales document flow: follow a sales order to its deliveries and invoices with VBFA
Read the document flow table VBFA to list everything that follows a sales order, name each follow-up document type and print a readable flow.
3 steps · 4 explained parts - Modern ABAPIntermediate
Let the database add up: GROUP BY, SUM, HAVING and a size label on sales items (VBAP)
Count the items and add up the net value per sales document in one SELECT, keep only documents with more than one item, and label each as Large or Small in the program.
4 steps · 5 explained parts - Modern ABAPBeginner
Who may do this? AUTHORITY-CHECK with S_TCODE and a clear message
Check in code whether the current user may start a transaction, handle the answer for the allowed and the not-allowed case, and know where to look when the check fails.
3 steps · 4 explained parts - Modern ABAPBeginner
Modern ABAP: total per customer with VALUE, FOR, GROUP BY, REDUCE and an ABAP Unit test
Write readable modern ABAP: build tables with VALUE, filter with FOR WHERE, group and sum with GROUP BY and REDUCE, read safely with table expressions, and protect the logic with an ABAP Unit test.
4 steps · 13 explained parts - Modern ABAPIntermediate
Modern ABAP expressions: VALUE, FOR, FILTER, COND, SWITCH and REDUCE
Build a table in one expression, loop with FOR, keep only the open rows with FILTER, label values with COND and SWITCH and add them up with REDUCE.
3 steps · 8 explained parts - Modern ABAPIntermediate
ABAP field symbols and data references: change rows in place and read any structure
Raise prices inside an internal table without copying rows, print every field of a structure by name with RTTI and create a variable at runtime with CREATE DATA.
3 steps · 5 explained parts - Modern ABAPIntermediate
ABAP OO: an interface, inheritance and polymorphism with shipping methods
Define an interface for shipping methods, implement it in three classes, redefine one method in a subclass and call all of them through the interface.
4 steps · 8 explained parts - Modern ABAPAdvanced
ABAP Unit with a test double: test business logic without the database
Split a discount service from its data source with an interface, inject a hand-written test double and write ABAP Unit tests for the limits of the discount tiers.
4 steps · 8 explained parts - Modern ABAPIntermediate
Application log: write messages and a caught exception with the BAL API and read them in SLG1
Create a log with an object and subobject, add a status message and an exception, save it and find it afterwards in transaction SLG1 or in ADT.
3 steps · 5 explained parts - Modern ABAPIntermediate
Clean core: read products with the released CDS views I_Product and I_ProductDescription
Replace a direct read of the tables MARA and MAKT with the released CDS views that ABAP Cloud allows, and take the language from a released class.
3 steps · 3 explained parts - Modern ABAPAdvanced
AMDP and a CDS table function: aggregate orders in SQLScript on HANA
Push a calculation into the database with an ABAP-managed database procedure (AMDP) behind a CDS table function, read it with ABAP SQL, and learn when this is the right tool.
3 steps · 4 explained parts - Modern ABAPIntermediate
Lock before you change: ENQUEUE and DEQUEUE a sales order and see the lock in SM12
Set a lock on a sales order with the standard lock object EVVBAK, handle the case that another user already holds it, release it, and look at the lock in transaction SM12.
3 steps · 4 explained parts - Modern ABAPIntermediate
Run a report in the background: JOB_OPEN, SUBMIT VIA JOB, JOB_CLOSE and check it in SM37
Create a background job from code, give it a report and a parameter, start it at once, and find its status and spool output in transaction SM37.
4 steps · 4 explained parts - Modern ABAPIntermediate
How much stock do we have? Add up MARD per plant and show the base unit from MARA
Read unrestricted-use stock per storage location from MARD, add it up per material for one plant, and show the base unit of measure from MARA.
3 steps · 3 explained parts - Modern ABAPBeginner
Internal table basics: add, find, change, delete and sort rows
Build a small order-item list in memory and practise the six moves every ABAP developer uses daily: APPEND, INSERT, READ TABLE, change in place, DELETE and SORT.
5 steps · 6 explained parts - Modern ABAPIntermediate
Print or get a PDF from an Adobe Form: FP_JOB_OPEN, generated function module, FP_JOB_CLOSE
Call an existing Adobe Form (form builder, transaction SFP) from ABAP: open the job, find the generated function module, call it with your data, close the job and return the PDF.
4 steps · 5 explained parts - Modern ABAPIntermediate
User exit in sales orders: stop the save when an item quantity is too high (MV45AFZZ)
Use the classic SD user exit USEREXIT_SAVE_DOCUMENT_PREPARE to check the items of a sales order just before it is saved and show an error message.
3 steps · 3 explained parts - Modern ABAPBeginner
Interactive classic report: click a flight connection to see its flight dates (HIDE and AT LINE-SELECTION)
Write a basic list with WRITE, remember the key of each line with HIDE, and show a detail list when the user double-clicks a line.
3 steps · 4 explained parts - Modern ABAPBeginner
Write your own function module with an exception and call it (also from another system with RFC)
Create a function module that returns a customer name, raises an exception when the customer does not exist, and call it locally and through RFC.
3 steps · 4 explained parts - Modern ABAPIntermediate
Call a standard BAPI: create a sales order, read the RETURN table, then commit or roll back
Create a sales order with BAPI_SALESORDER_CREATEFROMDAT2, check the RETURN messages for errors, and finish with BAPI_TRANSACTION_COMMIT or ROLLBACK.
3 steps · 4 explained parts - Modern ABAPIntermediate
BAdI from both sides: define your own BAdI (SE18), call it with GET BADI, and implement it
Create an enhancement spot with a BAdI, call it in your program with GET BADI and CALL BADI, then write a separate implementation that changes the behaviour without touching the program.
3 steps · 3 explained parts - Modern ABAPIntermediate
Classic BDC: fill a transaction with CALL TRANSACTION USING and list the messages
Build a BDCDATA table with the screen and field values from an SHDB recording, run the transaction without display, and print the system messages.
3 steps · 4 explained parts - Modern ABAPBeginner
Dialog program (module pool): a screen with an input field, a Show button and a transaction code
Build a first screen 0100 where the user types a customer number, presses Show and sees the name, using PBO and PAI modules and a GUI status.
3 steps · 3 explained parts - Business Data CloudIntermediate
Read an SAP data product in SAP Databricks and inspect its meaning and personal-data tags
Query an SAP data product that is mounted as a catalog in SAP Databricks, then read the comments, keys and personal-data tags that SAP delivers with it.
3 steps · 5 explained parts - Business Data CloudAdvanced
Prove a data product is fresh, unique and complete: three SQL checks
Three SQL checks you can schedule: how old is the newest change, are there duplicate keys, and do status counts match between the product and your own table.
3 steps · 3 explained parts - Business Data CloudAdvanced
Prepare S/4HANA data for a data product: a CDS view enabled for extraction with delta
Create a CDS view entity on a custom table and annotate it for data extraction with change data capture, so a data platform can load only what changed.
2 steps · 3 explained parts - Modern ABAPIntermediate
Who changed what? Read change documents of a sales order from CDHDR and CDPOS
Find the last changes of a sales order in the change document header CDHDR, read the changed fields from CDPOS, and print user, date, field, old and new value.
3 steps · 3 explained parts - Modern ABAPAdvanced
The most common performance bug: SELECT in a loop versus one join, measured with ST05
Read the customer name for 200 orders once with a SELECT inside a loop and once with a single join, measure both, and prove the difference with the SQL trace in ST05.
3 steps · 5 explained parts - Modern ABAPIntermediate
Document numbers without gaps in logic: NUMBER_GET_NEXT and a number range object
Create a number range object once, then take the next number in code, handle every error of the function module and understand why numbers can have gaps.
3 steps · 4 explained parts - Modern ABAPIntermediate
ABAP SELECT: FOR ALL ENTRIES versus INNER JOIN (and its three traps)
Compare two ways to read flights with their airline names, see why FOR ALL ENTRIES needs an emptiness check, silently removes duplicates, and why a join is usually simpler.
3 steps · 8 explained parts - Modern ABAPIntermediate
ABAP report with ALV (CL_SALV_TABLE): optimized columns and a clickable order id
Show an internal table as an ALV grid with CL_SALV_TABLE, set column texts, stripe the rows and react when the user clicks an order id hotspot.
3 steps · 7 explained parts - Modern ABAPBeginner
ABAP report: selection screen, events and input checks
Build a classic report with a selection screen, set defaults in INITIALIZATION, check the input in AT SELECTION-SCREEN and read the data in START-OF-SELECTION.
3 steps · 6 explained parts - Modern ABAPIntermediate
Classic ABAP internal tables: SORT, DELETE ADJACENT DUPLICATES, COLLECT and AT END OF
Use the classic internal table statements that fill most older programs: sort, remove duplicates, add up with COLLECT, and print group totals with AT END OF and SUM.
4 steps · 6 explained parts - Modern ABAPIntermediate
Classic ALV report with REUSE_ALV_GRID_DISPLAY: field catalog and double click
Show sales orders in a classic ALV grid with a hand-built field catalog, a layout with zebra stripes, a total on the net value and a click on the order number that opens the order.
4 steps · 4 explained parts - Modern ABAPIntermediate
ABAP: call a BAPI, read the RETURN table, then commit or roll back
Create a sales order with BAPI_SALESORDER_CREATEFROMDAT2 in test mode first, check the RETURN table for errors and only then commit with BAPI_TRANSACTION_COMMIT.
4 steps · 5 explained parts - Modern ABAPIntermediate
ABAP BAdI: define one, call it from your code and implement it
Create an enhancement spot and a BAdI definition, call the BAdI from a program with GET BADI and CALL BADI, and write an implementation that a customer can switch on or change.
3 steps · 5 explained parts - Modern ABAPIntermediate
Smart Forms: design a form and print it from ABAP
Design a small order form in SMARTFORMS with a header structure and an item table, then call the generated function module from a report and check the result.
3 steps · 5 explained parts - Modern ABAPBeginner
ABAP class-based exceptions: raise your own exception and catch it
Create a custom exception class, raise it from a method when the input is wrong, and catch the specific error, a system error and everything else in the right order.
3 steps · 6 explained parts - Modern ABAPBeginner
ABAP strings: split, clean, validate with a regex and format a number
Turn one messy text line into clean fields with SPLIT, CONDENSE, a regular expression check, REPLACE and a string template.
3 steps · 5 explained parts - Modern ABAPIntermediate
ABAP internal tables: standard, sorted, hashed and secondary keys
See when to pick a standard, sorted or hashed internal table, and how a secondary key speeds up a second kind of lookup on the same data.
3 steps · 6 explained parts - CDS viewsBeginner
CDS view entities: association, path expression and aggregation (revenue per customer)
Model sales orders and customers with CDS view entities, join them lazily with an association, aggregate revenue per customer, and read the result from ABAP SQL.
4 steps · 12 explained parts - CDS viewsBeginner
CDS view entity with an input parameter and a CASE expression
Build a CDS view entity that takes a year as a parameter, filters on it and turns a one-letter status code into readable text with CASE, then call it from ABAP SQL.
2 steps · 6 explained parts - CDS viewsIntermediate
CDS value help and search annotations for Fiori elements
Give the Employee field a searchable value help dialog by defining a value help view and connecting it with @Consumption.valueHelpDefinition.
4 steps · 4 explained parts - CDS viewsIntermediate
CDS access control (DCL): show each user only the leave requests they may see
Protect a CDS view with an access control role that checks an authorization object, so users see only the employees they are authorized for.
4 steps · 4 explained parts - CDS viewsBeginner
CDS date functions: days requested, a reminder date and an urgency flag
Calculate the number of leave days, a reminder date and a 'starts soon' flag inside a CDS view entity with DATS_DAYS_BETWEEN, DATS_ADD_DAYS and the session date.
2 steps · 5 explained parts - CDS viewsIntermediate
CDS text view: show a readable status text in the right language
Create a text view for status codes, mark language and text fields with semantic annotations, and connect it to the leave view with @ObjectModel.text.association.
3 steps · 3 explained parts - CDS viewsIntermediate
CDS view entities: LEFT OUTER JOIN, CASE, CAST and UNION ALL
Show orders even when their customer is missing with a left outer join, translate codes with CASE and CAST, and combine live and archived orders into one list with UNION ALL.
4 steps · 9 explained parts - ABAP RAPIntermediate
Build a managed RAP business object: Leave Request with approve action
Create a managed RAP business object from table to Fiori preview: CDS interface view, behavior definition with a determination, validation and action, behavior class, projection and OData V4 service.
6 steps · 23 explained parts - ABAP RAPIntermediate
RAP parent and child: a sales order with items (composition)
Model an order header with item lines as one RAP business object using a composition, then create a header and two items in one step with EML.
4 steps · 8 explained parts - ABAP RAPIntermediate
RAP action with an input parameter: Reject a leave request with a reason
Add a Reject action that asks the user for a reason in a dialog, using an abstract entity as the parameter structure, and store the reason on the request.
4 steps · 10 explained parts - ABAP RAPIntermediate
RAP instance feature control: disable Approve once a request is decided
Use instance feature control so the Approve button is greyed out for requests that are already approved or rejected, and the backend refuses the action as well.
3 steps · 4 explained parts - ABAP RAPAdvanced
RAP draft handling: let users save work in progress and activate it later
Turn the Leave Request business object into a draft-enabled one: draft table, draft actions, total ETag and the matching projection, so a half-filled request survives a closed browser.
3 steps · 8 explained parts - ABAP RAPAdvanced
RAP additional save: write an audit log row on every create, update and delete
Keep the managed save of a RAP business object and add your own database write in the same transaction with an additional save and the method SAVE_MODIFIED.
5 steps · 15 explained parts - ABAP RAPAdvanced
RAP custom entity: serve a list from ABAP code with paging and a filter
Expose data that is not in a database table (an API, a calculation, a file) as an OData entity with a CDS custom entity and a query provider class that handles paging, count and filter.
4 steps · 8 explained parts - ABAP RAPIntermediate
Call your RAP business object from ABAP with EML (create, read, approve, commit)
Use Entity Manipulation Language to create, read and approve Leave Requests from plain ABAP, with the same validations and determinations as the Fiori app.
4 steps · 6 explained parts - ODataBeginner
OData V4: read, filter, create and update with HTTP and JavaScript
Read $metadata, use $filter, $select, $orderby, $top and $count, then create and update a Leave Request with a CSRF token, ETag and session cookie from JavaScript.
3 steps · 12 explained parts - SAP BTPIntermediate
SAP BTP: build and deploy a Node.js CAP service (Support Desk with a Resolve action)
Create a CAP project, model data with CDS, expose an OData V4 service, add validation and a bound action in JavaScript, test locally and deploy to SAP BTP Cloud Foundry.
6 steps · 19 explained parts - SAP BTPIntermediate
SAP BTP CAP: consume an S/4HANA OData service (Business Partner) and expose it
Import the S/4HANA Business Partner API into a CAP project, test it with an automatic local mock, then connect it to a BTP destination for the real system.
4 steps · 4 explained parts - SAP BTPBeginner
SAP BTP CAP: an order with items (composition) and a deep insert
Model Orders and OrderItems with a composition in CAP, create an order together with its items in one request, read it back with $expand and add a check in a handler.
4 steps · 6 explained parts - SAP BTPBeginner
SAP BTP CAP: validate input with annotations, no code
Make a field required, limit a number to a range, check a text format and mark a field read-only with CAP annotations, then see the errors in the HTTP answer.
3 steps · 4 explained parts - SAP BTPAdvanced
SAP CAP Node.js: a bound action to approve an order and a function for the open total
Model an order service in CAP, protect the status field from direct changes, add a bound action that approves one order with checks and an unbound function that returns a total.
4 steps · 9 explained parts