2012-02-06 17 views
1

oracleで以下のクエリを手伝ってもらえますか?
その人がフレンドリーネームを持っている場合は、それを「検索」基準にマッチさせるために使用します。それ以外の場合は、実名の列と一致するようにしてください。WHERE句のOracle CASE

select * from people where 
case when customer_friendlyname is null then realname like '%abcd%' 
else 
case when customer_friendlyname is not null then customer_friendlyname like '%abcd%' 
end 
end 

ありがとうございました。

答えて

2

を使用して一致しようとしますOracleでは、ブール式は他のタイプの式と同様に扱うことはできません。たとえば、CASEの式は評価できません。だから、これを書き直す必要があります。

WHERE (CASE WHEN customer_friendlyname IS NULL 
      THEN realname 
      ELSE customer_friendlyname 
     END 
    ) LIKE '%abcd%' 

をそれはthe built-in NVL functionを利用するために簡単です、と書く:あなたは両方のブランチで同じLIKE '%abcd%'述語を持っているので、この場合は

、あなたはちょうどそれを織り込むことができ

WHERE NVL(customer_friendlyname, realname) LIKE '%abcd%' 
2
SELECT * 
FROM people 
WHERE (customer_friendlyname LIKE '%abc%') 
    OR (customer_friendlyname is null and realname LIKE '%abc%') 

あなたが実際に、ここにこれをケースを必要としないまたは句が、一致しませんヌルた最初のフレンドリ名を尽くす、それが本当の名前

+0

'realname'が' 'abc''だが' customer_friendlyname'が '' def''ならば、OPはそのレコードが返されることを望んでいないと思います。 – ruakh

+0

ruakhが正しいです! – user1191463

+0

@ user1191463が修正されました –

1

また、それをこのように書くことができます。

select * from people where 
case 
    when customer_friendlyname is null and realname like '%abcd%' 
    then 1 
    when customer_friendlyname is not null and customer_friendlyname like '%abcd%' 
    then 1 
    else 0 
end = 1 

しかし、より多くの表現がある場合はより便利です。