具有相同表达式的多个案例陈述

时间:2017-11-16 16:15:15

标签: tsql case sql-server-2014

我尝试评估特定列以返回五个不同的列 - 但这些列基于CASE语句中的相同表达式。

     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 1
          ELSE 0
     END AS [Invalid] ,
     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 0
          ELSE 1
     END AS [validMICcode] ,
     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 0
          ELSE 1
     END AS [validSerialNumber] ,
     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 0
          ELSE 1
     END AS [validFormat] ,
     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 0
          ELSE 1
     END AS [validProductionYear] ,

我觉得这样会导致有问题的表/列被搜索五次,但我无法弄清楚如何重写它 - 或者甚至是否可能 - 进行一次模式搜索并根据一次搜索。

我尝试了不同的变体,但我无法为此问题提出正确的语法:

CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 1
          ELSE 0          
            CASE WHEN 1 THEN 1 END AS [Invalid]
            CASE WHEN 0 THEN 0 END AS [validMICode]
            CASE WHEN 0 THEN 0 END AS AS [validSerialNumber]
            CASE WHEN 0 THEN 0 END AS AS [validFormat]
            CASE WHEN 0 THEN 0 END AS AS [validProductionYear]
    END

2 个答案:

答案 0 :(得分:1)

一种方法是子查询和按位NOT。

select
    result Invalid,
    ~result validMICcode,
    ~result validSerialNumber,
    ~result validFormat,
    ~result validProductionYear
from
(

   select 
     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' 
       THEN CAST(1 As bit) 
       ELSE CAST(0 As bit) 
     End result 
   from ...
) tbl

答案 1 :(得分:0)

你可以用CTE做到这一点..

with cte as(
select *,
CASE 
   WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' 
      THEN 1
      ELSE 0  
END as SomeColumn)

select *,
            CASE WHEN SomeColumn = 1 THEN 1 END AS [Invalid]
            CASE WHEN SomeColumn = 0 THEN 0 END AS [validMICode]
            ...
from cte