oracle 函数unioncode,【小计】PostgreSQL实现Oracle的decode函数功能

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值