Join only if the above query returns records

4

Good people,

I would like to know what approach they would take to make a union only if the above query, from the union, returns values. Consider that the tables are compatible EX:

SELECT * FROM Tabela1
UNION
SELECT * FROM Tabela2 
/*Esta query so deve ser executada apenas se a query acima, select * from Tabela1, tiver devolvido algum valor*/

Regards, Leandro

    
asked by anonymous 02.06.2016 / 19:11

3 answers

0

Only if you use the table above to filter the second

declare @Tabela1 table
(
    id int
)

declare @Tabela2 table
(
    id int
)

--insert into @Tabela1 values (1),(2),(3),(4)
insert into @Tabela2 values (1),(2),(3),(5)


SELECT * FROM @Tabela1
UNION
SELECT * FROM @Tabela2 
where exists (SELECT top 1 id FROM @Tabela1)
    
02.06.2016 / 19:24
0

I tested the statement below and it worked (I think it's easy to understand):

select * from bairro where id = 1
   union
   select * from bairro where id > 15 and
     EXISTS (select FIRST 1 * from bairro where id = 1)
    
02.02.2017 / 17:41
-1
SELECT
*
FROM(
    SELECT * FROM Tabela1
    UNION ALL
    SELECT * from Tabela2) as aux
WHERE (SELECT COUNT(*) FROM Tabela1) > 0
    
13.11.2017 / 19:44