T-SQL join table only when the table is not empty

邮差的信 提交于 2019-12-12 12:14:14

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/14195117/t-sql-join-table-only-when-the-table-is-not-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!