【小計】PostgreSQL實現Oracle的decode函數功能

來源:互聯網
上載者:User

標籤: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函數功能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.