Oracle和Cognos Framework Manager中decode妙用,CASE WHEN也可以!

我们都知道Decode函数可以用来做什么作用,如果这个不知道的话,请找下度娘。

那么,今天就来介绍一下,在WHERE条件语句里面使用Decode函数。

由浅入深,先一步一步来。。

with tmp as(
  select 1 val,null flag from dual union all
  select 1 val,'a' flag from dual union all
  select 2 val,'b' flag from dual union all
  select 3 val,'c' flag from dual
)
select 1,decode(flag,'a',1,'b',2,'c',3, 0) 
from tmp

这样,我们查出来的数据为:

 1 1 --》a
 1 2 --》b
 1 3 --》c

这一步,没有问题。看这个,晕了没有:

with tmp as(
  select 1 val,null flag from dual union all
  select 1 val,'a' flag from dual union all
  select 2 val,'b' flag from dual union all
  select 3 val,'c' flag from dual
)
select 1,decode(flag,'a',1,'b',2,'c',3, 0) 
from tmp
where decode(val,1,1,2) 
      = decode(flag,'a',1,'b',2,'c',3, 0) 
;

换一种写法:

with tmp as(
  select 1 val,null flag from dual union all
  select 1 val,'a' flag from dual union all
  select 2 val,'b' flag from dual union all
  select 3 val,'c' flag from dual
)
select 1,decode(flag,'a',1,'b',2,'c',3, 0) 
from tmp
where (val=1 and flag = 'a')
        or
      (val <> 1 and flag = 'b')

 这样看懂了吧。。

其实decode在这种情况下只是一种简写而已。

但是对于Cognos FrameworkManager,就是用来匹配参数了。

就是用于根据传递过来的参数的不同,使用不同的过滤条件。

with tmp as(
  select 1 val,null flag from dual union all
  select 1 val,'a' flag from dual union all
  select 2 val,'b' flag from dual union all
  select 3 val,'c' flag from dual
)
select 1,decode(flag,'a',1,'b',2,'c',3, 0) 
from tmp
 and decode(#prompt('display','string') #,'1',1,
              			    '2',val,
              			    '0') 
	=
       decode(#prompt('display','string') #, '1',1,
              			    '2',2,
              			     '1')

解释一下,当display参数为1 的时候,不过滤。

当display参数为2的时候,过滤val =2 。

当display参数为空或者其他的时候,过滤掉所有的 0=1。

活学活用。。

今天又发现,CASE WHEN也能如此方便地使用:

with tmp as(
select 1 id, 'kelly' name from dual union all
select 2 id, 'sam' name from dual union all
select 3 id, 'jason' name from dual union all
select 4 id, 'kobe' name from dual union all
select 5 id, null name from dual
)
select id, name from tmp
where id = case when length(name)>1 then length(name)
           else 5 end
;

猜你喜欢

转载自dacoolbaby.iteye.com/blog/1716891