4

I have the following tables with one column (RecordID):

TableOne
101
102
103
104
105
106

TableTwo
101
102
103
104

and want to make join between them only when TableTwo is not empty. This could be done with sample IF statement, but in my real situation this would lead to a lot of code duplication.

I have try the following:

SELECT * FROM
TableOne T1
WHERE exists (select 1 from TableTwo where T1.RecordID=RecordID)
      and exists (select 1 from TableTwo)

using this answer , but the same logic is not working for me - it works only when the second table is not empty, if it is empty, nothing is return.

Has anyone know if this is possible?

Community
  • 1
  • 1
gotqn
  • 42,737
  • 46
  • 157
  • 243

1 Answers1

6

I assume you want to select all if there's no row in TableTwo. You need an OR and NOT EXISTS:

SELECT 
   T1.* 
FROM
   TableOne T1
WHERE 
   EXISTS(SELECT 1 from TableTwo WHERE T1.RecordID=RecordID)
   OR NOT EXISTS(SELECT 1 FROM TableTwo)

SQL-Fiddle

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939