【问题标题】:Control JOIN type between two tables based on parameter value根据参数值控制两个表之间的 JOIN 类型
【发布时间】:2014-09-24 12:30:58
【问题描述】:

这就是我想使用 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?

【问题讨论】:

  • 你说的是dynamic SQL,它只能在you understand the pros and cons之后使用
  • 所以我必须为这个单一的更改使整个查询动态化?
  • 您需要一个动态查询,但有一个问题,在加入时,您是否需要准确说明要加入的列?

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


【解决方案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

【讨论】:

    【解决方案2】:

    你也许可以做这样的事情:

    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 并根据@isclosed 的值在#table1#table2 的键上过滤NULLs。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 2021-07-08
      相关资源
      最近更新 更多