21

Im trying to use case to vary the value im checking in a where clause but I'm getting the error:

incorrect syntax near the keyword 'CASE'

SQL Server 2005

select * 
from   table
where  ((CASE when adsl_order_id like '95037%'
         then select '000000'+substring(adsl_order_id,6,6)
         ELSE select adsl_order_id
       END)
       not in (select mwebID from tmp_csv_dawis_bruger0105)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
fatjoez
  • 211
  • 1
  • 2
  • 5

6 Answers6

44

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
Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
Randy Minder
  • 47,200
  • 49
  • 204
  • 358
6

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)
Joey
  • 344,408
  • 85
  • 689
  • 683
1

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
 )
Pondlife
  • 15,992
  • 6
  • 37
  • 51
0

I came to this question looking for an answer thinking WHERE CASE ... would be the solution. I could not adapt the answers to my problem, but this technique to use a parameter that could be null, partial, or specific, works:

CREATE PROC myproc  @vJobID VARCHAR (11) 
AS
SELECT * FROM Jobs 

WHERE Jobs.JobID like coalesce(@vJobID+'%','%') 

HTH

-1

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

Peter Radocchia
  • 10,710
  • 2
  • 34
  • 56
-1

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.

Ian Warburton
  • 15,170
  • 23
  • 107
  • 189