using CASE in T-SQL in the where clause?

≯℡__Kan透↙ 提交于 2019-11-29 05:57:41
Randy Minder

Here is one way to include a case statement in a Where clause:

SELECT * FROM sometable
WHERE 1 = CASE WHEN somecondition THEN 1 
    WHEN someothercondition THEN 2
    ELSE ... END

You could try

SELECT *
FROM table
WHERE (SELECT CASE WHEN adsl_order_id LIKE '95037%'
              THEN '000000' + SUBSTRING(adsl_order_id, 6, 6)
              ELSE adsl_order_id
              END)
      NOT IN (select mwebID from tmp_csv_dawis_bruger0105)

A correlated subquery is one possibility:

select * 
from mytable
where not exists (
    select * 
    from 
        tmp_csv_dawis_bruger0105
    where 
        mwebID = 
        CASE when mytable.adsl_order_id like '95037%' then '000000' + substring(mytable.adsl_order_id,6,6)
        ELSE mytable.adsl_order_id END
 )

You have one too many opening parentheses before the CASE expression.

Put it in the SELECT clause...

select *, (CASE when adsl_order_id like '95037%'
         then '000000'+substring(adsl_order_id,6,6)
         ELSE adsl_order_id
       END) AS Id
from   table
where  not in (select mwebID from tmp_csv_dawis_bruger0105)

Also, you don't need to "SELECT" the result of the CASE.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!