使用OR运算符在where子句中选择case

时间:2013-09-28 18:04:06

标签: sql-server case where-clause or-operator

我有一个学生表,其中有一个名为SEN的列。 SEN包含每个记录的S,A,P或N.在我的WHERE子句中,我想根据SEN中的值过滤我的结果集。我的SELECT语句包含一个名为subgroup的变量,该变量由参数填充。当过滤到单个值时,我已设法使其工作,即SEN列,即:

   SEN = CASE
           WHEN @Subgroup = 'SENA' THEN 'A'
           WHEN @Subgroup = 'SENP' THEN 'P'
           WHEN @Subgroup = 'SENS' THEN 'S'
           WHEN @Subgroup = 'SENNo' THEN 'N'
       END 

但我想过滤学生有A,P或S的位置,并使用参数值'SENYes'触发此过滤器。我的下面的代码不起作用,但可以说明我的要求。

   SEN = CASE 
           WHEN @Subgroup = 'SENYes' THEN 'A' OR 'P' OR 'S'
           WHEN @Subgroup = 'SENA' THEN 'A'
           WHEN @Subgroup = 'SENP' THEN 'P'
           WHEN @Subgroup = 'SENS' THEN 'S'
           WHEN @Subgroup = 'SENNo' THEN 'N'
       END 

更新:

在我的代码中使用IN运算符:

   SEN = CASE 
           WHEN @Subgroup = 'SENA' THEN 'A'
           WHEN @Subgroup = 'SENP' THEN 'P'
           WHEN @Subgroup = 'SENS' THEN 'S'
           WHEN @Subgroup = 'SENNo' THEN 'N'
       END
   OR
   (@SubGroup='SENYes' AND SEN IN ('A','P','S'))

2 个答案:

答案 0 :(得分:1)

您可以使用条件

Where 
(@SubGroup='SENYes' and SEN IN ('A','P','S'))
OR
(SEN = SubString(@SubGroup,4,1))

例如

declare @std table (SEN varchar(1))
Insert into @std
Select 'A'
UNION Select 'P'
UNION Select 'S'
UNION Select 'N'

declare @Subgroup varchar(10)
--change commented for testing
--Select @SubGroup='SENA'
Select @SubGroup='SENYes'

Select * from @std
Where 
(@SubGroup='SENYes' and SEN IN ('A','P','S'))
OR
(SEN = SubString(@SubGroup,4,1))

答案 1 :(得分:0)

DECLARE @AllowedValues TABLE (SEN CHAR(1) PRIMARY KEY);
IF @Subgroup IN ('SENA', 'SENP', 'SENS', 'SENNo')
BEGIN
    INSERT @AllowedValues (SEN)
    VALUES (
       CASE 
           WHEN @Subgroup = 'SENA' THEN 'A'
           WHEN @Subgroup = 'SENP' THEN 'P'
           WHEN @Subgroup = 'SENS' THEN 'S'
           WHEN @Subgroup = 'SENNo' THEN 'N'
       END)    
END
ELSE IF @Subgroup = 'SENYes'
BEGIN
    INSERT @AllowedValues (SEN)
    SELECT 'A' UNION ALL
    SELECT 'P' UNION ALL
    SELECT 'S'
END
ELSE 
BEGIN
    RAISERROR('Invalid subgroup', 16, 1);
    RETURN; -- Needed if there is no TRY - CATCH
END

SELECT ...
FROM ...
WHERE SEN IN (SELECT v.SEN FROM @AllowedValues v);
--                   ^ You need to use alias here to avoid nasty surprises