如何在cluase和in子句中应用案例

时间:2015-05-26 11:32:16

标签: sql

这是我的查询。 @ScoreCount可能包含零或不包含零。如果它包含零,则应考虑零,以及null和空字符。如何在where子句中执行此操作?

DECLARE @ScoreCount varchar(50)
SET @ScoreCount = '2,5,0'
SELECT e.name,e.id,e.degisnation 
FROM tblEmployee e INNER JOIN Department d ON d.id = e.did 
WHERE e.degisnation = @designation AND ScoreCount IN (@ScoreCount)

所以我这样做了。

SELECT e.name,e.id,e.degisnation 
FROM tblEmployee e INNER JOIN Department d ON d.id = e.did 
WHERE e.degisnation =@designation AND
    CASE WHEN ScoreCount is null THEN 0 
         WHEN ScoreCount ='' THEN 0 
         ELSE ScoreCount END IN (2, 5, 0)

这是正确的方法吗?

这里我将数据库值设为null,然后''首先应用in子句。我有一个查询。如何执行。根据我的说法

step 1 from --- > Result1
step2 apply join on Result1 -->Result2
step3 apply where clause first part on Result2 -->Result3
step4 apply case part on Result3 then msidn in part check -->Result4
setp 5 select Result4

首先,它将result3的所有记录更改为适当的msidn然后检查msidn in子句或逐个更改result3的记录到适当的msidn然后检查子句中的msidn

2 个答案:

答案 0 :(得分:2)

您在case条款中不需要where。只需使用传统逻辑:

select e.name, e.id, e.degisnation
from tblEmployee e inner join
     Department d
     on d.id = e.did
where e.degisnation = @designation and
      (ScoreCount is null or ScoreCount = '' or ScoreCount in (2, 5) )

我从列表中删除了0。我认为它只是前两个条件。

答案 1 :(得分:0)

我想如果你只使用:

...
    AND COALESCE(ScoreCount, 0) IN (0, 2, 5)
--or
-- AND ISNULL(ScoreCount, 0) IN (0, 2, 5)

会处理它们。