標籤:oracle postgresql 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;
本文出自 “積跬步至千裡” 部落格,請務必保留此出處http://chnjone.blog.51cto.com/4311366/1658845
【小計】PostgreSQL實現Oracle的decode函數功能