如何在条件之间使用SQL CASE语句

时间:2014-07-01 13:18:08

标签: sql sql-server case

我是SQL案例陈述的新手。当我使用案例陈述时,'在'之间。从而表示错误。查询以下

SELECT CASE
       WHEN @Divid=1 THEN CONVERT(varchar(20),datename(mm,m.dob)) + ' ' + CONVERT(varchar(20),datename(DAY ,m.dob))
       ELSE CONVERT(varchar(20),datename(mm,m.ActualDOB)) + ' ' + CONVERT(varchar(20),datename(DAY ,m.ActualDOB))
   END 'DOB' ,
       m.FirstName + ISNULL(m.LastName,'') 'Name',
                                           m.EmployeeNo ,
                                           m.Customer
FROM sEmployeeMaster m
JOIN lDivision d ON m.BizVertical=d.Division
WHERE d.DivisionID= @Divid
  AND CASE
      WHEN @Divid=1 THEN MONTH(dob) BETWEEN MONTH(getdate()) AND MONTH(getdate()+2)
           AND DAY(dob)BETWEEN DAY(getdate()) AND DAY(getdate()+2)
      ELSE MONTH(ISNULL(m.ActualDOB,dob) BETWEEN MONTH(getdate()) AND MONTH(getdate()+2)
           AND DAY(m.ActualDOB,
                   dob)BETWEEN DAY(getdate()) AND DAY(getdate()+2)
  END

1 个答案:

答案 0 :(得分:5)

您不能在where子句中使用分支和条件语句。您只需将其更改为完整的逻辑语句:

 WHERE d.DivisionID= @Divid
    AND (
        (@Divid = 1 AND
            MONTH(dob) BETWEEN MONTH(getdate()) AND  MONTH(getdate()+2)
            AND DAY(dob)BETWEEN DAY(getdate()) AND  DAY(getdate()+2)) 
        OR
        (@Divid <> 1 AND
            MONTH(ISNULL(m.ActualDOB,dob) BETWEEN MONTH(getdate()) AND  MONTH(getdate()+2)
            AND DAY(m.ActualDOB,dob)BETWEEN DAY(getdate()) AND  DAY(getdate()+2)) 
        )