1

I have query like:

select * 
from BASE_TABLE
inner join (
    select * from TABLE_A
) t on BASE_TABLE.ID = t.ID

and want to make nested query conditional, something like:

select * 
from BASE_TABLE
inner join (
    if @var = 1 
        select * from TABLE_A
    else 
        select * from TABLE_B
) t on BASE_TABLE.ID = t.ID

Is it possible? Query is used inside stored procedure. Solution should work for SQL Server and Oracle or at least for SQL Server.

1

3 Answers 3

2

How about this:

SELECT
  * 
FROM
  BASE_TABLE
  INNER JOIN (
    SELECT col1, col2, colN FROM TABLE_A WHERE @var IN (1) -- "if"
    UNION
    SELECT col1, col2, colN FROM TABLE_B WHERE @var IN (2) -- "else if"
    UNION
    SELECT col1, col2, colN FROM TABLE_C WHERE @var NOT IN (1, 2) -- "else"
  ) t ON t.ID = BASE_TABLE.ID
Sign up to request clarification or add additional context in comments.

3 Comments

Could you explain why union fits here. Does it work properly if 2 result sets have the same rows?
Union fits here because the WHERE clauses are mutually exclusive. I thought that would be obvious.
The fact that you asked this question in the first place indicates an error in the database design. In a well-designed database you should not have to "switch tables" in a query.
0

I would do it like this (but then you need to specify fields; you can't use select * syntax):

select base.ID, base.Field1, base.Etc, Field1 = case when @var=1 then a.Field1 else b.Field1 end,
       Field2 = case when @var=1 then a.Field2 else b.Field2 end
  from BASE_TABLE base
  left join TABLE_A a on base.ID = a.ID
  left join TABLE_B b on base.ID = b.ID

Comments

0

please try below query

declare @var int=1  
declare @qry nvarchar(max)  
set @qry='select * from BASE_TABLE ('  
if @var=1  
set @qry=@qry+ 'select * from TABLE_A'  
else  
set @qry=@qry+ 'select * from TABLE_B'  

set @qry=@qry+')t on BASE_TABLE.ID = t.ID'

exec (@qry)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.