根据其他条件向左外连接添加条件 - SQL Server 2008

时间:2016-04-01 14:53:43

标签: sql sql-server sql-server-2008

我想根据其他条件在左外连接的“on”部分添加一个条件。我试图使用“case when”但SQL Server 2008会抛出语法错误(它对等号不满意)。这可能很容易,对不起,但我真的看不出如何解决这个问题。任何帮助将不胜感激。

@declare @timeMode int = 2;
...
...
select *
from #AllPeriods ap 
left outer join #results r on ap.p1= r.p1 
                           and ap.p2 = r.p2 
                           and DATEDIFF(S,ap.StartPeriod, r.StartPeriod) = 0 
                           and 
                             case 
                                when @timeMode != 4 
                                   then DATEDIFF(s,ap.EndPeriod, r.EndPeriod) = -1 
                                   else DATEDIFF(s,ap.EndPeriod, r.EndPeriod) = 0 
                             end 

1 个答案:

答案 0 :(得分:0)

您可以使用case,但SQL Server无法将布尔表达式识别为可行选项。所以,这是一种使用case的方法:

from #AllPeriods ap left outer join
     #results r
     on ap.p1 = r.p1 and 
        ap.p2 = r.p2 and 
        DATEDIFF(second, ap.StartPeriod, r.StartPeriod) = 0 and 
        DATEDIFF(second, ap.EndPeriod, r.EndPeriod) = (case when @timeMode <> 4 then -1 else 0 end)

但是,不需要case。您可以使用OR

from #AllPeriods ap left outer join
     #results r
     on ap.p1 = r.p1 and 
        ap.p2 = r.p2 and 
        DATEDIFF(second, ap.StartPeriod, r.StartPeriod) = 0 and 
        ((@timeMode <> 4 and DATEDIFF(second, ap.EndPeriod, r.EndPeriod) = -1) or
         (@timeMode = 4 and DATEDIFF(second, ap.EndPeriod, r.EndPeriod) = 0)
        )

注意:如果@timeMode could be为空,这不太正确。