在sql查询中为一个条件添加where条件

时间:2015-06-09 10:44:15

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

我需要为SQL查询添加where条件,意味着当dept id变为9时我只需要条件,否则我不需要。

我写了下面的查询,方法是否正确?

SELECT 
b.DeptId,
b.DeptName,
a.SurveyID,
a.SurveyName,
a.Status,
a.AllUsers, 
IsNull(a.SelectedUsers,'') as SelectedUsers,
a.OpenDate,
a.CloseDate,
e.Role as RoleName 
from Surveys a 
inner join Departments b 
on a.deptid=b.deptid 
left outer join
 surveyUsers c 
on c.surveyid=a.SurveyID 
and c.empCode= 9902
left outer join [360HRSurveyEmployee] d 
on d.surveyid=a.SurveyID 
left outer join [360HRSurvey] e 
on e.sempid = c.empCode 
and e.empid = d.empid 
where ( c.empCode= 9902 or a.AllUsers = 1 ) 
and a.status in (1) 
and a.OpenDate <= '6/9/2015' 
and a.CloseDate >= '6/9/2015'
and CASE WHEN DeptId == 9 
         THEN e.Role IS NOT NULL END
 order by b.DeptID,a.SurveyID 

请注意上面查询中我添加案例的最后三行:

and CASE WHEN DeptId == 9 
         THEN e.Role IS NOT NULL END
 order by b.DeptID,a.SurveyID 

我也遇到语法错误

Incorrect syntax near '='.

3 个答案:

答案 0 :(得分:0)

and CASE WHEN DeptId == 9

此比较只需要一个=符号。

答案 1 :(得分:0)

您需要使用单=

CASE WHEN DeptId = 9 
     THEN e.Role END

你想用这条线做什么? THEN e.Role IS NOT NULL END

答案 2 :(得分:0)

如果我理解正确,你只需要DeptId不是9的行,或者DeptId不是null。此外,你粗略地忽视你的资本化的一致性会伤害我。这是什么野兽?!

SELECT
    b.DeptID, b.DeptName,
    a.SurveyID, a.SurveyName, a.Status, a.AllUsers,
    ISNULL(a.SelectedUsers,'') as SelectedUsers,
    a.OpenDate, a.CloseDate, e.Role as RoleName
FROM
    Surveys AS a
    INNER JOIN Departments AS b
        ON a.DeptID = b.DeptID
    LEFT OUTER JOIN SurveyUsers AS c
        ON (c.SurveyID = a.SurveyID AND c.EmpCode = 9902)
    LEFT OUTER JOIN [360HRSurveyEmployee] AS d
        ON d.SurveyID = a.SurveyID
    LEFT OUTER JOIN [360HRSurvey] AS e
        ON (e.EmpID = c.EmpCode AND e.EmpID = d.EmpID)
WHERE
    (
        c.EmpCode = 9902
        OR a.AllUsers = 1
    )
    AND a.Status = 1
    AND a.OpenDate <= '6/9/2015'
    AND a.CloseDate >= '6/9/2015'
    AND (
        a.DeptID != 9
        OR e.Role IS NOT NULL
    )
ORDER BY
    a.DeptID,
    a.SurveyID;