zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

PostgreSQL Oracle兼容性之 - REMAINDER

Oraclepostgresql 兼容性
2023-09-14 09:00:26 时间

在PostgreSQL数据库中常用的取余函数为mod,Oracle另外还提供了一个取余的函数remainder,它与mod的区别在于,mod取余时用了floor处理,而remainder使用round处理。

算法
1. mod

PG Oracle mod

mod(x,y) = x - trunc(x/y)*y 

经典 mod

mod(x,y) = x - y * FLOOR(x/y) 

2. remainder

remainder(x,y) = x - y * ROUND(x/y) 

REMAINDER(n2, n1)

REMAINDER returns the remainder of n2 divided by n1.

This function takes as arguments any numeric datatype or any nonnumeric datatype that can be implicitly converted to a numeric datatype.

Oracle determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that datatype, and returns that datatype.

The MOD function is similar to REMAINDER except that it uses FLOOR in its formula, whereas REMAINDER uses ROUND.


If n1 = 0 or m2 = infinity, then Oracle returns
An error if the arguments are of type NUMBER
NaN if the arguments are BINARY_FLOAT or BINARY_DOUBLE.


If n1 != 0, then the remainder is n2 - (n1*N) where N is the integer nearest n2/n1.


If n2 is a floating-point number, and if the remainder is 0, then the sign of the remainder is the sign of n2.

Remainders of 0 are unsigned for NUMBER values.

PostgreSQL remainder

了解算法之后,PG就很容易实现remainder的函数了。

postgres=# create or replace function remainder(int8,int8) returns int8 as $$

 select ($1 - $2 * round($1::numeric/$2::numeric))::int8 ;

$$ language sql strict;

CREATE FUNCTION

postgres=# create or replace function remainder(int4,int4) returns int4 as $$

 select ($1 - $2 * round($1::numeric/$2::numeric))::int4 ;

$$ language sql strict;

CREATE FUNCTION

postgres=# create or replace function remainder(int2,int2) returns int2 as $$

 select ($1 - $2 * round($1::numeric/$2::numeric))::int2 ;

$$ language sql strict;

CREATE FUNCTION

postgres=# create or replace function remainder(numeric,numeric) returns numeric as $$

 select ($1 - $2 * round($1/$2)) ; 

$$ language sql strict;

CREATE FUNCTION

验证结果

postgres=# select remainder(-11,4);

 remainder 

-----------

(1 row)

postgres=# select mod(-11,4);

 mod 

-----

(1 row)

参考

http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions133.htm

http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions088.htm

Count


【.NET 6】使用EF Core 访问Oracle+Mysql+PostgreSQL并进行简单增改操作与性能比较 唠嗑一下。都在说去O或者开源,但是对于数据库选型来说,很多人却存在着误区。例如,去O,狭义上讲,是去Oracle数据库。但是从广义上来说,是去Oracle公司产品或者具有漂亮国垄断地位和需要商业授权的数据库产品。
关于PostgreSQL数据库兼容Oracle数据库闪回查询的实现方案 注:关于在PostgreSQL上面实现Oracle数据库的闪回功能(闪回查询 闪回表 闪回删除…)的这个想法已经有很长时间了,但是鉴于本人的能力 精力和身体条件 迟迟没有完成。期间也有很多的小伙伴跟我一起研究过这个功能,但是最终都因为各种各样的问题 没有做下去。Oracle数据库闪回功能跨越版本较大,功能也比较强大 在PostgreSQL数据库上实现,需要对数据库内核有很深入的理解 两大数据库不同的底层原理也终将影响各自的实现策略,PostgreSQL标记删除就地插入的特点和基于事务快照行可见性的特性是我们可以开发PostgreSQL闪回查询的大前提。本文主要介绍 实现闪回查询的 一种实现方案