Select joining table based on condition

时间:2016-01-08 07:41:08

标签: sql-server join

I have 3 tables

  1. TableA
  2. TableB
  3. TableC

I need to join TableA to either with TableB or TableC based on parameters passed. ie

select * from 
TableA A 
join (TableB on <Joining Condition> /  TableC on <joining condition> )

i tried with below query

select * from 
TableA A 
join (
   case when paramB<>'' then TableB on <Joining Condition>
   case when paramC<>'' then TableC on <joining condition>
 )

But, this is giving syntax error. can anyone help.?

Solution:

create table #temp (<columns>)
if paramB<>''
begin
   select * from 
   TableA A 
   join TableB on <Joining Condition>
end
else if paramB<>''
begin
  select * from 
   TableA A 
   join TableC on <Joining Condition>
end

3 个答案:

答案 0 :(得分:5)

您可以使用UNION ALL

select *
from a
join TableB on <join condition>
where paramB <> ''

union all

select *
from a
join TableC on <join condition>
where paramC <> ''

请注意,TableBTableC必须具有相同的列数且具有相同的数据类型,否则会产生错误。

答案 1 :(得分:1)

你可以尝试这样的事情:

  select *
  from a 
  left join b ON <Joining Condition>
  left join c ON <Joining Condition>
  where paramB <> '' or paramC <> ''

答案 2 :(得分:0)

步骤1:使用reqd.columns创建临时表 步骤2:如果paramB有值,则与TableB连接          否则加入TableC。

create table #temp (<columns>)
if paramB<>''
begin
   select * from 
   TableA A 
   join TableB on <Joining Condition>
end
else if paramB<>''
begin
 select * from 
 TableA A 
 join TableC on <Joining Condition>
end