Foreign Keys

You can also define the relationships between tables in the ABAP Dictionary by creating foreign keys.

Using foreign keys, you can easily create value checks for input fields. Foreign keys can also be used to link several tables in a view or a lock object.

Field Assignment in the Foreign Key

A foreign key links two tables T1 and T2 by assigning fields of table T1 to the primary key fields of table T2.

Table T1 is called the foreign key table (dependent table) and table T2 the check table (referenced table). The pair of fields for the two tables must have the same data type and length. One field of the foreign key table therefore corresponds to each key field of the check table. This field is called the foreign key field .

A foreign key permits you to assign data records in the foreign key table and check table. One record of the foreign key table uniquely identifies one record of the check table using the entries in the foreign key fields.

Check Field and Value Check

One of the foreign key fields is marked as the check field . This means that the foreign key relationship is maintained for this field.

When an entry is made in the check field, there is a check whether the check table contains a record with the key defined by the values in the foreign key fields. If this is so, the entry is valid. Otherwise the entry will be rejected by the system.

In this example the entry Field2 = 2 and Field4 = 2 would be rejected since T2 does not contain a record with the key Field5 = 2 and Field6 = 2.

If you do not want to check against all the key fields of the check table, you can remove fields of the foreign key table from the assignment of the fields to the check table with Generic and Constant Foreign Keys.

How the Input Check Works

A SELECT statement is generated from the definition of the foreign key. If an entry is made in the check field, this SELECT statement is submit. If a suitable record of the check table is found, the entry is valid. Otherwise the entry will be rejected.

The corresponding SELECT statement has the following form for the foreign key table shown in the above graphic:

SELECT * FROM T2 WHERE T2-FIELD5 = T1-FIELD2 AND T2-FIELD6 = T1-FIELD4.

A screen entry for check field Field2 is therefore only valid if the check table contains a record with the entries made in the screen for Field2 and Field4 as key.

Table SBOOK in the Flight Model contains the customer flight bookings for a carrier. The flight bookings can be made by travel agencies or directly at the counter of the carrier. If the booking was made at a counter, its number is stored together with the booking in field COUNTNUM of table SBOOK.

You must make sure that only correct desk numbers can be entered. All the counters are entered in table SCOUNTER. The necessary input checks can be defined by creating a foreign key for check field COUNTNUM.

See also:

Multi-Structured Foreign Keys

Semantic Attributes of a Foreign Key

Creating Foreign Keys