带有Col1<> Col2的where子句中的CASE

时间:2011-12-12 10:38:46

标签: sql tsql case where-clause

在以下示例数据中,我需要选择

所有记录
  1. ModelOut=ModelOut(全部)
  2. ModelIn<>ModelOut
  3. ModelIn=ModelOut
  4. 问题是ModelIn<>ModelOut,因为我不知道怎么用where子句中的CASE语句来做。

    Declare @type int;
    SET @type=2; --- ModelIn <> ModelOut  
    
    Create table #Data(ID int, ModelIn varchar(10), ModelOut varchar(10))
    INSERT INTO #Data
        SELECT 1 AS ID,'A' AS ModelIn, 'B' AS ModelOut
        UNION ALL 
        SELECT 2 AS ID,'B' AS ModelIn, 'B' AS ModelOut
        UNION ALL 
        SELECT 3 AS ID,'C' AS ModelIn, 'D' AS ModelOut
        UNION ALL 
        SELECT 4 AS ID,'D' AS ModelIn, 'D' AS ModelOut
    
    SELECT * FROM #Data
    WHERE ModelOut =
        CASE  @type
            WHEN 1 THEN ModelOut --- all
            WHEN 2 THEN ???      --- ModelIn <> ModelOut
            WHEN 3 THEN ModelIn  --- ModelOut = ModelIn
        END
    ;
    
    Drop table #Data;
    

3 个答案:

答案 0 :(得分:4)

您的查询不需要CASE(事实上,这只会使这里的事情变得复杂,我会说)。只需写下这样的查询:

SELECT * FROM #Data
WHERE (
    @type = 1 OR
   (@type = 2 AND (ModelIn <> ModelOut)) OR
   (@type = 3 AND (ModelOut = ModelIn))
);

答案 1 :(得分:1)

作为一个案例,你可以再做一次CASE。如果您提供的WHERE子句不是更强制查询的简化方差 - 我会使用nyarlathotep建议的方法和重构的WHERE子句。

 WHERE ModelOut =
        CASE  @type
            WHEN 1 THEN ModelOut --- all
            WHEN 2 THEN 
                       CASE WHEN ModelIn <> ModelOut THEN ModelOut
                            ELSE ModelOut  + '_'
                       END
            WHEN 3 THEN ModelIn  --- ModelOut = ModelIn
        END

所以当ModelIn <> ModelOut时 - 整个CASE将返回true,否则为false

答案 2 :(得分:0)

you should change your select query in this way

Declare @type int;
    SET @type=2; 
    SELECT * FROM #Data
    WHERE (@type = 1 )
    union
    SELECT * FROM #Data
    WHERE  (@type = 2 AND (ModelIn <> ModelOut)) 
      union 
      SELECT * FROM #Data
    WHERE    
          (@type = 3 AND (ModelOut = ModelIn))

可能会有所帮助