概述
對與熟練維護oracle數據庫的DBA來說,在接觸PostgreSQL數據庫時,會覺得缺少在oracle非常常用的函數,特別是在做存儲過程遷移時,就會經常出現這樣的情況,比如decode函數,nvl函數等等,在這里會將這些缺失的函數做一下整理,方便以后使用。
nvl()函數
nvl(value1, value2) 當value1 為null時返回value2,否則返回value1.
coalease(value1,value2,value3....)函數返回參數中第一個非null的值,所以可以替換nvl()函數;
也可以使用case when end實現nvl()的目的
wm_concat()函數
PostgreSQL 中也有行轉列的函數,但是針對不同的數據類型,需要使用不同的函數,
字符串:
SELECT string_agg(a, ',' ORDER BY a) FROM table;
數組:
SELECT array_agg(a ORDER BY b DESC) FROM table;
json/jsonb:
select json_agg(expression) from table;
select jsonb_agg(expression) from table;
xml:
select xmlagg(expression) from table;
sys_guid()函數
獲取隨機數
CREATE or replace FUNCTION pg_catalog.sys_guid() RETURNS varchar AS $$
BEGIN
RETURN md5(random()::text || clock_timestamp()::text);
END;
$$ LANGUAGE plpgsql;
unix_timestamp()函數
將日期時間轉換成時間戳
create or replace function pg_catalog.unix_timestamp(text) returns int
as $$
select (date_part('epoch',$1::timestamp))::int;
$$
LANGUAGE SQL IMMUTABLE;
from_unixtime()函數
將時間戳轉換成日期時間
create or replace function pg_catalog.from_unixtime(int) returns timestamp
as $$
select to_timestamp($1)::timestamp - '8h'::interval;
$$
LANGUAGE SQL IMMUTABLE;
decode()函數
decode(條件,值1,返回值1,值2,返回值2,…值n,返回值n,缺省值)
當條件=值1時,返回“返回值1”,當條件=值2時,返回“返回值3”。。。。當沒有符合的值時,返回缺省值
create or replace function pg_catalog.decode(variadic p_decode_list text[])
returns text as
$$
declare
v_len integer := array_length(p_decode_list, 1);
v_ret text;
begin
if v_len >= 3 then
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;
函數來源:https://www.cnblogs.com/mgt001/p/7810503.html
最后修改時間:2021-11-13 00:11:54
「喜歡這篇文章,您的關注和贊賞是給作者最好的鼓勵」
關注作者
【版權聲明】本文為墨天輪用戶原創內容,轉載時必須標注文章的來源(墨天輪),文章鏈接,文章作者等基本信息,否則作者和墨天輪有權追究責任。如果您發現墨天輪中有涉嫌抄襲或者侵權的內容,歡迎發送郵件至:contact@modb.pro進行舉報,并提供相關證據,一經查實,墨天輪將立刻刪除相關內容。




