postgres中的函數


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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM