开发者

SQL DB2 - conditional logic in WHERE clause

开发者 https://www.devze.com 2023-04-10 14:23 出处:网络
I need to pull back records based on a location ID, but I\'ve got two fields that MAY contain the incoming criteria....

I need to pull back records based on a location ID, but I've got two fields that MAY contain the incoming criteria....

something like this

SELECT * FROM tbl
WHERE myVar = locationID
    IF Locati开发者_如何学GoonID = 0
      myVar = location2ID

this is a 'logical' example...

I think I can do

WHERE myVar = CASE WHEN locationID = 0 THEN location2ID ELSE locationID END

although I've read that CASE in a WHERE clause should be avoided...? why? or is this OK? - either way it FAILS

WHERE CASE WHEN locationID=0 THEN location2ID=myVAr ELSE locationID=myVar END

also FAILS

thx

Sorry for the confusion lads - didn't mean to be "ambiguous" - looks like #2 will do what I want - but for the clarification requested here is the issue...

the table stores TWO locations, let's call then CURRENT_LOC and ORIGINAL_LOC... in most cases these will BOTH have data, but in some cases the 'thing' hasn't moved... so the CURRENT_LOC is '0'. MY issue is I'll be passing in a LOCATION ID, I want the records where CURRENT_LOC matches OR if the the CURRENT_LOC=0 then I ALSO want the ORIGINAL_LOC... where that matches...

does that help the discussion? I hope.


WHERE myVar = COALESCE(NULLIF(locationID, 0), location2ID)

Alternatively,

WHERE (
       (locationID <> 0 AND myVar = locationID) 
       OR 
       (locationID = 0 AND myVar = location2ID)
      ) 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号