PostgreSQL实现Oracle的decode函数功能

PostgreSQL实现Oracle的decode函数功能

原文链接:https://blog.csdn.net/weixin_34242509/article/details/92974392

在数据库中创建一个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相同,至少三个参数 * 实现原理: 1、VARIADIC 允许变参; 2、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; -- 测试1select 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;-- 测试2with 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;
  1.  

相关文章