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; -- 測試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;