[英]SQL DB2 - conditional logic in WHERE clause
I need to pull back records based on a location ID, but I've got two fields that MAY contain the incoming criteria.... 我需要根据位置ID拉回记录,但是我有两个字段可能包含传入的条件。
something like this 像这样的东西
SELECT * FROM tbl
WHERE myVar = locationID
IF LocationID = 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...? 尽管我读过应该避免在WHERE子句中使用CASE ...? 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... 很抱歉让小伙子们困惑-并不是说要“模棱两可”-看起来#2可以满足我的要求-但是在这里要求澄清的是问题...
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'. 该表存储两个位置,然后调用CURRENT_LOC和ORIGINAL_LOC ...在大多数情况下,它们都将具有数据,但是在某些情况下,“事物”没有移动...因此CURRENT_LOC为'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...
我的问题是我要传递一个LOCATION ID,我想要CURRENT_LOC匹配的记录,或者如果CURRENT_LOC = 0,那么我也想要ORIGINAL_LOC ...匹配的位置...
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)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.