Skip to main content

SQL Table Commands

In this section we will dive into SQL Statements in ABAP. We will try to cover all CRUD operations with important querying methods.

Table Used in This examples

We will use a table called EKKO and a ZTable make by us called ZSTUDENT_TABLE

These are some fields we will be using in the examples.

Note: Columns Name(Technical Name) When querying you will use Technical name

You can view these in Transaction SE16N

Table Namefields
ZSTUDENT_TABLESTNAME(NAME),STAGE(AGE), SSN(SSN),Study(MAJOR)
EKKOCreatedBy(ERNAM), Currency(WAERS),CreatedOn(AEDAT),Purchasing Doc.(EBELN)

Retrieving Data from Tables

Similar to SQL language we use SELECT operator to select from tables.

ABAP Select

In ABAP, you need to put the retrieved data into an Internal Table.


SELECT * from EKKO. " This will result in an error
SELECT * FROM EKKO INTO TABLE @DATA(IT_TABLE). " inline declaration

Get All


" Selecting all columns
SELECT * from EKKO into table @data(it_table).
" Looping through all records in the table
loop at it_table into data(wa_ekko).
" Displaying Created By names.
write: / wa_ekko-ERNAM.
endloop

Where Operator

You can query fields just like SQL.



select * from zstudent_table into table @DATA(it_t)
where age > 20
and ( major = 'SWE' or major = 'COE' or major = 'CHE' ) .

Limit Result

You can limit number rows. We added UP TO ( num ) ROWS

select * from zstudent_table into table @DATA(it_t)
UP TO 5 ROWS
where age > 20 and ( major = 'SWE' or major = 'COE' or major = 'CHE' ) .

Creating Data

Inserting One record

You can inserting data using INSERT INTO table values work_area

This example define a variables.



Data: wa_uni type ZUNIVERSITY.

SELECTION-SCREEN BEGIN OF BLOCK x1 with frame title text-001.
PARAMETERS: p_name type ZUNIVERSITY-name,
p_id type ZUNIVERSITY-id.

SELECTION-SCREEN END OF block x1.


wa_uni-name = p_name.
wa_uni-id = p_id.

insert into zuniversity values wa_uni.

Delete Record

Delete one record


DELETE from zstudent_table where id = 1000.

This will delete the record matching the condition.

Updating record

Updating complete record

DATA: wa_student TYPE zstudent_table.

" First, read the record
SELECT SINGLE * FROM zstudent_table
WHERE ssn = '12345'
INTO @wa_student.

IF sy-subrc = 0.
" Modify the fields you want to change
wa_student-name = 'Abdullah Updated'.
wa_student-age = 26.
wa_student-major = 'SWE'.

" Update the record
UPDATE zstudent_table FROM @wa_student.

IF sy-subrc = 0.
MESSAGE 'Record updated successfully' TYPE 'S'.
ELSE.
MESSAGE 'Failed to update record' TYPE 'E'.
ENDIF.
ELSE.
MESSAGE 'Record not found' TYPE 'E'.
ENDIF.

Updating fields in a Record

You can update some fields of a record without needing to retrieve whole record.


update zstudent_table
SET name = @('Abdullah Updated22')
SET age = @(100)

where ssn =10000