How to merge two results into a query conditionally

0

Talk, guys!

Would anyone know how I can use a UNION ALL conditionally?

Example:

DECLARE @cond INT = 1

SELECT * FROM table1
IF(@cond = 1)
BEGIN
   UNION ALL
   SELECT * FROM table2
END

The idea is this but this does not work. How could I join the table only if the condition was true?

It needs to be in this context because I have several tables that will be chosen by the user, so it could be: t1, t1 + t2, t1 + t2 + t3, t1 + t3, t2 + t3 + t5, ...

    
asked by anonymous 06.09.2018 / 04:35

1 answer

0

If you already use the variable declaration structure, you will have no problem / constraints. The idea is to create a variable to concatenate union (according to its validation) and then execute:

DECLARE @cond INT = 1
DECLARE @sql VARCHAR(255)

SELECT @sql = 'SELECT * FROM table1'

IF(@cond = 1)
BEGIN
   SELECT @sql = @sql + ' UNION ALL SELECT * FROM table2'
END

EXEC @sql
    
06.09.2018 / 13:13