SQL INSERT

Posted by Bryan Chong


The INSERT statement is ABAP is very powerful.

Syntax

INSERT INTO <target_database_tab> <database_tab_lines>.

Target, is the database table name, and also can be a variable of table.

Lines, it can be a single record or multiple records.

Insert for Single Line

We could have 3 ways to insert single line to database table.

By declaring a variable, and store the information into it, and then insert to database table.

First method will be

INSERT INTO table VALUES theLineVariable.

Second method is

INSERT table FROM theLineVariable.

The code different for first and second method are first method using “INTO & VALUES”, where second method using “FROM”. It makes the code shorter.

The third method, we can use the declared table to store the information, and then insert to database table. This method is look very simple. But, if we use this method, the table that declared, are not allowed to use again in other part.

INSERT table.

Example1: 3 ways to insert data.

Part A: Using first method

TABLES KNA1.
DATA cu TYPE KNA1.
cu-KUNNR = '007'.
cu-NAME1 = 'Bryan'.
INSERT INTO KNA1 VALUES cu.

Part B: Using second method

TABLES KNA1.
DATA cu TYPE KNA1.
cu-KUNNR = '007'.
cu-NAME1 = 'Bryan'.
INSERT KNA1 FROM cu.

Part C: Using third method

TABLES KNA1.
KNA1-KUNNR = '007'.
KNA1-NAME1 = 'Bryan'.
INSERT KNA1.

Insert for multiple lines

The concept of this is similar to SELECT multiple records to a variable. Here we need to create the Hashed Table, it will act like a temporary table with same structure with the original table.

We also can define the accepting rules for the insert to prevent runtime error during execution. This can be added to the end of the statement “ACCEPTING DUPLICATE KEYS”.

Example 2: To insert multiple line

* Define the hashed table and the line of hashed variable
DATA: hKNA1 TYPE HASHED TABLE OF KNA1
            WITH UNIQUE KEY MANDT KUNNR,
      lKNA LIKE LINE OF hKNA1.

* Now insert data into the hashed table
lKNA-KUNNR = '008'. lKNA-NAME1 = 'John'.
INSERT lKNA INTO TABLE hKNA1. 

lKNA-KUNNR = '009'. lKNA-NAME1 = 'Marry'.
INSERT lKNA INTO TABLE hKNA1.

lKNA-KUNNR = '010'. lKNA-NAME1 = 'Steven'.
INSERT lKNA INTO TABLE hKNA1.

* This line is to insert data from hashed table to physical table
INSERT KNA1 FROM TABLE hKNA1 ACCEPTING DUPLICATE KEYS.

Unknown's avatarAbout Bryan Chong
分享烹饪甜品小食为主 Mainly about cooking, desserts, snacks. 我不是专业的厨师,也不是专业的烘培师。只不过是为了兴趣而已。不一定所以东西都是正确的。多多指教 Email: bryan.chong.jw@gmail.com / bryan.chong.jw@outlook.my

One Response to SQL INSERT

  1. Matt Ther's avatar Matt Ther says:

    this is clear.. Thank you Bryan..

Leave a comment

Design a site like this with WordPress.com
Get started