-1

我有一个学生表,其中有一列名为 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'))
4

2 回答 2

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))
于 2013-09-28T19:42:53.193 回答
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 
于 2013-09-28T18:24:51.823 回答