根据参数值控制两个表之间的JOIN类型

时间:2014-09-24 12:30:59

标签: sql sql-server-2008 sql-server-2012-express

这就是我想用SQL Server做的事情:

declare @isclosed int
set @isclosed=0
declare @jointype varchar(50)

if(isclosed=0)
begin
set @jointype ='left outer join'
end

else
begin
set @jointype ='right outer join'
end


select * from #table1 @jointype  #table2
union
select * from table3

如何使用参数进行JOIN?

2 个答案:

答案 0 :(得分:1)

你正在寻找这样的东西......鉴于你的结构(比特值控制了正在执行的内容),你可能不必担心SQL注入。

declare @isclosed int
set @isclosed=0
declare @jointype varchar(50)

if(@isclosed=0)
  begin
    set @jointype ='left outer join'
  end

else
  begin
    set @jointype ='right outer join'
  end

DECLARE @SQL VARCHAR(4000)
SET @SQL = 

'
SELECT *
FROM
    #table1 
     ' + @jointype  + '
    #table2 ON 
        -- add something here as your JOIN condition

UNION

SELECT * 
FROM table3
'

EXECUTE sp_executesql @SQL

答案 1 :(得分:0)

你或许可以做这样的工作:

declare @isclosed int
set @isclosed=0

-- Since @isclosed can't be equal to 0 and at the same time not equal to 0,
-- only one of the following queries (the ones UNION ALL'd together) will return
-- records.

select * 
from   #table1 
     left outer join  
       #table2 on [whatever]
where (@isclosed=0)
union all 
select *
from   #table1
     right outer join
       #table2 on [whatever]
where (@isclosed <> 0)

union
select * 
from   table3

另一种选择是尝试使用FULL OUTER JOIN并在NULL#table1的键上过滤#table2,具体取决于@isclosed的值。