2012-02-06 129 views
1

有人可以帮助我在oracle中进行下面的查询吗?
逻辑是,如果该人拥有友好名称,请将其用于与“搜索”条件相匹配。否则,请尝试与真实姓名栏匹配。Oracle CASE在WHERE子句中

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表达式无法对它们进行评估。所以你需要重写这个。

在这种情况下,因为你必须在两个分支同样LIKE '%abcd%'谓词,你可以只是因素吧:

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

但它容易制造的the built-in NVL function使用,并写上:

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 2012-02-06 03:05:13

+0

ruakh是对的! – user1191463 2012-02-06 03:07:34

+0

@ user1191463已修复 – 2012-02-06 03:09:45

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 

但是,如果您有更多的表达方式,它会更方便。