首页 > 数据库 > 国内数据库 > 循序渐进丨MogDB 数据库的三种函数稳定性关键字
一、Oracle 中类似的函数稳定性关键字(DETERMINISTIC)
----带DETERMINISTIC的现象
create or replace function f_t(i_p int) return number DETERMINISTIC is
i_rtn number;
begin
i_rtn := i_p * dbms_random.value(1,10);
return i_rtn;
end;
select LEVEL,f_t(1) FROM DUAL CONNECT BY LEVEL<1=10;
----不带DETERMINISTIC的现象
create or replace function f_t(i_p int) return number is
i_rtn number;
begin
i_rtn := i_p * dbms_random.value(1,10);
return i_rtn;
end;
select LEVEL,f_t(1) FROM DUAL CONNECT BY LEVEL<1=10;

二、MogDB 数据库的三种函数稳定性状态

01
IMMUTABLE(非常稳定)
02
STABLE(稳定)
CREATE OR REPLACE FUNCTION func_out_num() RETURNS INTEGER AS
$$
BEGIN
RAISE NOTICE 'Invoke the func.';
RETURN 6;
END;
$$ LANGUAGE PLPGSQL STABLE;
select func_out_num() from generate_series(1,10);
alter function func_out_num() immutable;
select func_out_num() from generate_series(1,10);

MogDB=# create table test_stable (id int, info text);
CREATE TABLE
MogDB=# insert into test_stable select generate_series(1,100000),random()::text;
INSERT 0 1000
MogDB=# create index idx_test_a on test(id);
CREATE INDEX
create or replace function func_stable() returns numeric as $$
declare
begin
return 2;
end;
$$ language plpgsql stable;

explain analyze select func_stable() from test_stable;

03
VOLATILE(不稳定)
MogDB=# create table test_volatile (id int, info text);
CREATE TABLE
MogDB=# insert into test_volatile select generate_series(1,1000),random()::text;
INSERT 0 1000
MogDB=# create index idx_test on test(id);
CREATE INDEX
create or replace function func_volatile(ida int) returns text as $$
declare
result text;
begin
update test_volatile set info='xiaoguaishou' where id=ida returning info into result;
return result;
end;
$$ language plpgsql volatile;


“
作者简介
/ Author Introduction
阎书利 / 云和恩墨PG技术顾问
PostgreSQL ACE,《快速掌握 PostgreSQL 版本新特性》一书副主编,中国PG分会认证讲师,PGfans 2021年度MVP,Gauss松鼠会2021年度优秀会员,拥有PGCM、OCP(MySQL)等十多项数据库认证,目前主要从事于 PostgreSQL、openGauss / MogDB 的运维以及去O工作。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29715045/viewspace-3024649/ ,如需转载,请注明出处,否则将追究法律责任。