Application Development Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 

ABAP SQL join where the joining fields are based on a condition

former_member636171
Participant
0 Kudos

Hi all,

I want to join tables (TAB1 and TAB2) together on two columns depending on whether one of the columns is empty or not.
If TAB1-FIELD1 is not empty then I want to join on FIELD1, else I want to join on FIELD2.

I could do this by selecting TAB1 into an internal table and then doing a select for each line in the table but there must be a better way to do this?

Any help is appreciated.

Thanks,
Birgir

1 ACCEPTED SOLUTION

mateuszadamus
Active Contributor

Hello bsnorrason

Check this out. Have not tested it, though.

SELECT *
  FROM table1
  JOIN table2
    ON ( ( table2~field1 = table1~field1 AND table1~field1 IS NOT NULL )
      OR ( table2~field2 = table1~field2 AND table1~field2 IS NOT NULL ) ).
Kind regards,
Mateusz
2 REPLIES 2

mateuszadamus
Active Contributor

Hello bsnorrason

Check this out. Have not tested it, though.

SELECT *
  FROM table1
  JOIN table2
    ON ( ( table2~field1 = table1~field1 AND table1~field1 IS NOT NULL )
      OR ( table2~field2 = table1~field2 AND table1~field2 IS NOT NULL ) ).
Kind regards,
Mateusz

Thanks, this worked almost flawlessly!
For my use case I had to switch IS NOT NULL for <> ''.

SELECT *
  FROM table1
  JOIN table2
    ON ( ( table2~field1 = table1~field1 AND table1~field1 <> '' )
      OR ( table2~field2 = table1~field2 AND table1~field2 <> '' ) ).