create or replace function decode(variadic p_decode_list text[])

returns text

as

$$

declare

-- 获取数组长度(即入参个数)

v_len integer := array_length(p_decode_list, 1);

-- 声明存放返回值的变量

v_ret text;

begin

/*

* 功能说明:模拟Oracle中的DECODE功能(字符串处理, 其它格式能够自行转换返回值)

* 参数说明:格式同Oracle相同,至少三个参数

* 实现原理: 一、VARIADIC 容许变参; 二、Oracle中的DECODE是拿第一个数依次和以后的偶数位值进行比较,相同则取偶数位+1的数值,不然取最后一位值(最后一位为偶数为,不然为null)

*/

-- 同Oracle相同当参数不足三个抛出异常

if v_len >= 3 then

-- Oracle中的DECODE是拿第一个数依次和以后的偶数位值进行比较,相同则取偶数位+1的数值

for i in 2..(v_len - 1) loop

v_ret := null;

if mod(i, 2) = 0 then

if p_decode_list[1] = p_decode_list[i] then

v_ret := p_decode_list[i+1];

elsif p_decode_list[1] <> p_decode_list[i] then

if v_len = i + 2 and v_len > 3 then

v_ret := p_decode_list[v_len];

end if;

end if;

end if;

exit when v_ret is not null;

end loop;

else

raise exception 'UPG-00938: not enough args for function.';

end if;

return v_ret;

end;

$$

language plpgsql;

-- 测试1

select decode('_a','_aa', 'x') a3,

decode('_a','_aa', 'x', 's') a4,

decode('_a', '_aa', 'x', '_b', 's') a5,

decode('_b', '_aa', 'x', '_b', 's') a5,

decode('_a', '_aa', 'x', '_b', 's', 'o', 'x', 'tt') a6;

-- 测试2

with xx as

(

select 'M' sex

union all

select 'F' sex

union all

select 'X' sex

union all

select 'Z' sex

union all

select '' sex

)

select sex, decode(sex, 'M', '男', 'F', '女', decode(sex, 'X', '变性', '其它')) from xx;

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐