1.编写一个只有入参,没有出参的函数:
CREATE OR REPLACE FUNCTION add(a NUMERIC, b NUMERIC) RETURNS NUMERIC AS $$ SELECT a+b; $$ LANGUAGE SQL;
执行函数:
[postgres@master ~]$ psql -d mydb -U zhang psql (10.5) Type "help" for help. mydb=> mydb=> mydb=> select add(3,4); add ----- 7 (1 row)
2.编写一个有入参和出参的函数:
CREATE OR REPLACE FUNCTION add1(in a NUMERIC, in b NUMERIC,out c numeric) AS $$ SELECT a+b; $$ LANGUAGE SQL;
这里有出参,RETURNS NUMERIC就去掉了。
执行函数:
mydb=> select add1(2,4); add1 ------ 6 (1 row) mydb=> select * from add1(2,4); c --- 6 (1 row) --可以观察到,显示的列头不一样。
3.编写一个两个入参,两个出参的函数:
CREATE OR REPLACE FUNCTION plus_and_minus(IN a INTEGER, IN b NUMERIC, OUT c NUMERIC, OUT d NUMERIC) AS $$ SELECT a-b, a+b; $$ LANGUAGE SQL;
执行函数:
mydb=> select plus_and_minus(7,5); plus_and_minus ---------------- (2,12) (1 row) mydb=> select * from plus_and_minus(7,5); c | d ---+---- 2 | 12 (1 row)
4.编写一个往表里插入数据
准备操作:
--创建测试表 create table student (id integer, name varchar(64)); create table employees (id integer, age integer); --table_new 需要在外部创建 create table table_new (id integer, name varchar(64), age integer); --插入测试数据 insert into student select generate_series(1, 100), 'lili_' || cast(random()*100 as varchar(2)); insert into employees select generate_series(1, 50), random()*100; select count(*) from student; select count(*) from employees;
过程创建如下:
create or replace function P_DWA_ERP_LEDGER_JQ_MONTH_NEW( v_mouth varchar(8), out v_retcode text, out v_retinfo text, out v_row_num integer) AS $BODY$ declare begin insert into table_new(id, name, age) select t.id, t.name, m.age from student t, employees m where t.id=m.id; GET DIAGNOSTICS V_ROW_NUM := ROW_COUNT; -- 执行成功后的返回信息 V_RETCODE := 'SUCCESS'; V_RETINFO := '结束'; --异常处理 EXCEPTION WHEN OTHERS THEN V_RETCODE := 'FAIL'; V_RETINFO := SQLERRM; end; $BODY$ language plpgsql;
执行过程:
mydb=> select * from P_DWA_ERP_LEDGER_JQ_MONTH_NEW('12'); v_retcode | v_retinfo | v_row_num -----------+-----------+----------- SUCCESS | 结束 | 50 (1 row) mydb=> select count(*) from table_new; count ------- 50 (1 row)