SQL INSERT
June 17, 2011 1 Comment
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.
this is clear.. Thank you Bryan..