在Join Condition中使用Case语句

时间:2018-03-15 16:12:39

标签: sql sql-server

我怎样才能做到这一点?我收到错误incorrect syntax near between

@STARTDATE, @ENDDATE, @CREATEDDATE -- INPUT PARAMETERS 

SELECT * 
FROM [DBO].[xxx] x
INNER JOIN [DBO].[yyy] y
    ON x.ID = y.ID 
   AND CASE WHEN @CREATEDDATE = 1 
            THEN x.CreatedDate BETWEEN @STARTDATE AND @ENDDATE 
            WHEN @CREATEDDATE = 0 
            THEN x.ClosedDate BETWEEN @STARTDATE AND @ENDDATE

2 个答案:

答案 0 :(得分:4)

SQL Server不会将布尔表达式视为case表达式可以返回的内容。实际上,不鼓励caseon条款中的where。您可以使用更基本的布尔操作轻松表达这一点:

SELECT *
FROM [DBO].[xxx] x INNER JOIN
     [DBO].[yyy] y
     ON x.ID = y.ID AND 
        ( (@CREATEDDATE = 1 AND x.CreatedDate BETWEEN @STARTDATE AND @ENDDATE) OR
          (@CREATEDDATE = 0 AND x.ClosedDate BETWEEN @STARTDATE AND @ENDDATE)
        )

答案 1 :(得分:0)

您可以尝试以下查询

SELECT * 
FROM [DBO].[xxx] x
INNER JOIN [DBO].[yyy] y
    ON x.ID = y.ID 
   AND CASE WHEN @CREATEDDATE = 1 AND x.CreatedDate BETWEEN @STARTDATE AND @ENDDATE THEN 1
            WHEN @CREATEDDATE = 0 AND x.ClosedDate BETWEEN @STARTDATE AND @ENDDATE  THEN 1
            ELSE 0 END = 1