Quantcast
Channel: Solved » switch-statement
Viewing all articles
Browse latest Browse all 5

Sql Switch Case in Where Clause

$
0
0

I tried searching around but couldn’t find anything that would help me out.

I’m trying to do this in SQL:

declare @locationType varchar(50);
declare @locationID int;

SELECT column1, column2
FROM viewWhatever
WHERE
CASE @locationType
    WHEN 'location' THEN account_location = @locationID
    WHEN 'area' THEN xxx_location_area = @locationID
    WHEN 'division' THEN xxx_location_division = @locationID

I know that I shouldn’t have to put ‘= @locationID’ at the end of each one but I can’t get the syntax even close to being correct. SQL keeps complaining about my ‘=’ on the first WHEN line…

Help!

Solution

declare @locationType varchar(50);
declare @locationID int;

SELECT column1, column2
FROM viewWhatever
WHERE
@locationID = 
  CASE @locationType
      WHEN 'location' THEN account_location
      WHEN 'area' THEN xxx_location_area 
      WHEN 'division' THEN xxx_location_division 
  END

The post Sql Switch Case in Where Clause appeared first on Solved.


Viewing all articles
Browse latest Browse all 5

Trending Articles