ABAP SQL - COALESCE Function
Hello Everyone!👋
SQL COALESCE Function in ABAP
The COALESCE function is extremely useful when working with optional or missing data. It accepts a list of at least two (and up to 255) arguments — COALESCE(arg1, arg2, …, argn) and returns the first non-null value in the list. If all values are null, it returns the last argument.
Here is a small example, We have three tables:
𝗹𝘁_𝘀𝗮𝗹𝗲𝘀𝗼𝗿𝗱𝗲𝗿𝘀: Contains sales orders with net values and customer IDs.
DATA(lt_salesorders) = VALUE tt_salesorder(
( salesorder = '1' netvalue = '100.00' customer = 'CUST_1' )
( salesorder = '2' netvalue = '100.00' customer = 'CUST_2' )
( salesorder = '3' netvalue = '100.00' customer = 'CUST_3' ) ).
𝗹𝘁_𝗰𝘂𝘀𝘁𝗼𝗺𝗲𝗿_𝗼𝗻𝗲 and 𝗹𝘁_𝗰𝘂𝘀𝘁𝗼𝗺𝗲𝗿_𝘁𝘄𝗼: Two datasets with customer names and address IDs.DATA(lt_customer_one) = VALUE tt_customer(
( customer = 'CUST_1' customername = 'Customer 1' addressid = 1 ) ).
DATA(lt_customer_two) = VALUE tt_customer(
( customer = 'CUST_2' customername = 'Customer 2' addressid = 2 ) ).
𝗹𝘁_𝗰𝘂𝘀𝘁𝗼𝗺𝗲𝗿_𝗮𝗱𝗱𝗿𝗲𝘀𝘀: Stores addresses linked by addressid.
DATA(lt_customer_address) = VALUE tt_customer_address(
( addressid = 1 address = 'Sitheri, Cuddalore' )
( addressid = 2 address = 'Velluvadi, Perambalur' ) ).
Some customers exist in lt_customer_one and others in lt_customer_two. Using COALESCE, we can fetch the appropriate customer name and address ID regardless of where the data resides. Once we get the non-null addressid, we join it with the customer address table to retrieve the full address.
SELECT FROM @lt_salesorders AS a
LEFT OUTER JOIN @lt_customer_one AS b ON b~customer = a~customer
LEFT OUTER JOIN @lt_customer_two AS c ON c~customer = a~customer
LEFT OUTER JOIN @lt_customer_address AS d ON d~addressid = COALESCE( b~addressid, c~addressid )
FIELDS a~salesorder,
a~netvalue,
a~customer,
COALESCE( b~customername, c~customername ) AS customername,
d~address AS customeraddress
INTO TABLE @DATA(lt_salesorders_with_customer).
✔ Output
Notes: This is an alternative for a case expression. and this function is available in CDS, OPEN SQL(ABAP 7.4+) and AMDP.
For more information, please check the official documentation: ABAP Help

Comments
Post a Comment