How to join two results in a conditional query

Asked

Viewed 37 times

0

Talk, you guys!

Would anyone know how to use a Union All on parole?

Example:

DECLARE @cond INT = 1

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

The idea is this but that way it doesn’t work. How could I join the table only if the condition were 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+T3, t1+T3, t2+T3+T5, ...

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 the union (according to its validation) and then run:

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
  • Hello! This returns an error telling me that I could not find the precedure: Could not find stored 'SELECT * FROM table1 ...'

  • Let me ask: the Procedure was created? Running the code without being a Procedure, works (if yes, the error may be in creating the proc). detail: union will only work if table1 and table2 have the same fields (names and quantities); if not, the columns that will be returned must be specified...

  • Thanks for the help but I solved the problem by creating a temporary table, so I can select if the condition is true and I put the results in this table, at the end I have all the results in a single select. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.