暂无图片
暂无图片
4
暂无图片
暂无图片
暂无图片

PostgreSQL 中缺少的 oracle 函数汇总

概述

对与熟练维护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进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论