1. 程式人生 > >PostgreSQL函式如何返回資料集

PostgreSQL函式如何返回資料集

以下主要介紹PostgreSQL函式/儲存過程返回資料集,或者也叫結果集的示例。 

背景: PostgreSQL裡面沒有儲存過程,只有函式,其他資料庫裡的這兩個物件在PG裡都叫函式。 函式由函式頭,體和語言所組成,函式頭主要是函式的定義,變數的定義等,函式體主要是函式的實現,函式的語言是指該函式實現的方式,目前內建的有c,plpgsql,sql和internal,可以通過pg_language來檢視當前DB支援的語言,也可以通過擴充套件來支援python等 

函式返回值一般是型別,比如return int,varchar,返回結果集時就需要setof來表示。 

一、資料準備

create table department(id int primary key, name text);
create table employee(id int primary key, name text, salary int, departmentid int references department);

insert into department values (1, 'Management'),(2, 'IT'),(3, 'BOSS');

insert into employee values (1, 'kenyon', 30000, 1);
insert into employee values (2, 'francs', 50000, 1);
insert into employee values (3, 'digoal', 60000, 2);
insert into employee values (4, 'narutu', 120000, 3);
二、例子
1.sql一例
create or replace function f_get_employee() 
returns setof employee 
as 
$$
select * from employee;
$$
language 'sql';
等同的另一個效果(Query)
create or replace function f_get_employee_query() 
returns setof employee 
as 
$$
begin
return query select * from employee;
end;
$$
language plpgsql;
查詢圖解如下
postgres=# select * from f_get_employee();
 id |  name  | salary | departmentid 
----+--------+--------+--------------
  1 | kenyon |  30000 |            1
  2 | francs |  50000 |            1
  3 | digoal |  60000 |            2
  4 | narutu | 120000 |            3
(4 rows)
查詢出來的函式還可以像普通的表一樣按條件查詢 ,但如果查詢的方式不一樣,則結果也不一樣,以下查詢方式將會得到類似陣列的效果
postgres=# select f_get_employee();
   f_get_employee    
---------------------
 (1,kenyon,30000,1)
 (2,francs,50000,1)
 (3,digoal,60000,2)
 (4,narutu,120000,3)
(4 rows)
因為返回的結果集類似一個表的資料集,PostgreSQL還支援對該函式執行結果進行條件判斷並過濾
postgres=# select * from f_get_employee() where id >3;
 id |  name  | salary | departmentid 
----+--------+--------+--------------
  4 | narutu | 120000 |            3
(1 row)
上面的例子相對簡單,如果要返回不是表結構的資料集該怎麼辦呢?看下面 

2.返回指定結果集 
a.用新建type來構造返回的結果集 

--新建的type在有些圖形化工具介面中可能看不到,
要查詢的話可以通過select * from pg_class where relkind='c'去查,c表示composite type

create type dept_salary as (departmentid int, totalsalary int);

create or replace function f_dept_salary() 
returns setof dept_salary 
as
$$
declare
rec dept_salary%rowtype;
begin
for rec in select departmentid, sum(salary) as totalsalary from f_get_employee() group by departmentid loop
  return next rec;
  end loop;
return;
end;
$$
language 'plpgsql';
b.用Out傳出的方式
create or replace function f_dept_salary_out(out o_dept text,out o_salary text) 
returns setof record as
$$
declare
    v_rec record;
begin
    for v_rec in select departmentid as dept_id, sum(salary) as total_salary from f_get_employee() group by departmentid loop
        o_dept:=v_rec.dept_id;
        o_salary:=v_rec.total_salary;  
        return next;
    end loop; 
end;
$$
language plpgsql;
執行結果:
postgres=# select * from f_dept_salary();
 departmentid | totalsalary 
--------------+-------------
            1 |       80000
            3 |      120000
            2 |       60000
(3 rows)

postgres=# select * from f_dept_salary_out();
 o_dept | o_salary 
--------+----------
 1      | 80000
 3      | 120000
 2      | 60000
(3 rows)
c.根據執行函式變數不同返回不同資料集
create or replace function f_get_rows(text) returns setof record as
$$
declare
rec record;
begin
for rec in EXECUTE 'select * from ' || $1 loop
return next rec;
end loop;
return;
end
$$
language 'plpgsql';
執行結果:
postgres=# select * from f_get_rows('department') as dept(deptid int, deptname text);
 deptid |  deptname  
--------+------------
      1 | Management
      2 | IT
      3 | BOSS
(3 rows)

postgres=# select * from f_get_rows('employee') as employee(employee_id int, employee_name text,employee_salary int,dept_id int);
 employee_id | employee_name | employee_salary | dept_id 
-------------+---------------+-----------------+---------
           1 | kenyon        |           30000 |       1
           2 | francs        |           50000 |       1
           3 | digoal        |           60000 |       2
           4 | narutu        |          120000 |       3
(4 rows)
這樣同一個函式就可以返回不同的結果集了,很靈活。 

參考:http://bbs.pgsqldb.com/client/post_show.php?zt_auto_bh=53950

相關推薦

vb 呼叫 Oracle 函式返回資料的例子

PL/SQL 程式碼:CREATE OR REPLACE PACKAGE "SCOTT"."PKG_TEST" AS       TYPE myrcType IS REF CURSOR;       FUNCTION get(strbarcode VARCHAR) RETUR

PostgreSQL函式如何返回資料

以下主要介紹PostgreSQL函式/儲存過程返回資料集,或者也叫結果集的示例。 背景: PostgreSQL裡面沒有儲存過程,只有函式,其他資料庫裡的這兩個物件在PG裡都叫函式。 函式由函式頭,體和語言所組成,函式頭主要是函式的定義,變數的定義等,函式體主要是函式的實現

oracle使用儲存過程返回資料

很多時候,我們想通過儲存過程獲得一個輸出集。我們知道sql server的儲存過程在執行之後,返回的就是一個集合。但是oracle如果要獲得一個輸出集合,就要麻煩一點了。     oracle獲得輸出集合是通過遊標實現的,而且遊標需要在package中進行宣告。下面就拿分頁的

Postgres自定義函式返回記錄(虛擬表結構)

CREATE OR REPLACE FUNCTION fun_get_real_inv_qty(pvOrderId varchar) RETURNS SETOF record AS $BODY$b

oracle呼叫儲存過程和函式返回結果

在程式開發中,常用到返回結果集的儲存過程,這個在MySQL和sql server 裡比較好處理,直接返回查詢結果就可以了,但在Oracle裡面 要 out 出去,就多了一個步驟,對於不熟悉的兄弟們還得出上一頭汗:),這裡我簡單介紹一下,以供參考,   1  定義包      

webService--返回資料

//Service.csusing System;                                   //引用System名稱空間下的類 using System.Web;                               //引用Web名稱空間

儲存過程&函式返回結果

--建立測試表 create table t01(id integer,name varchar2(10)); --建立測試資料 insert into t01(id,name) values (1,'a'); insert into t01(id,name) value

如何在Delphi中呼叫oracle的儲存過程返回資料

::::::本文的相關評價及說明資訊:::::: 【delphi+oracle報表解決方案(一)】delphi中呼叫oracle的儲存過程(分帶返回遊標,不返回值兩種)  關鍵字: delphi ,oracle儲存過程,遊標,返回資料集,報表 注:delphi 6+ oracle 8.1.6 一.建立包與

oracle 通過function 函式 返回結果

自己理解分三步走1.建立資料物件,用於儲存結果集中的結果。create or replace type room as object ( roomid varchar2(12), roomare

oracle pipelined返回函式 針對資料彙總統計 返回結果方法

/*開啟日誌輸出*/ Set serveroutput on ; /*建立型別*/ create or replace type type_flux_data_stat_o as object ( ifinoctetsbps number , ifoutoctetsbps number

Mybatis 返回Map & List動態列資料

 1、xml檔案中的resultType都指定為HashMap: <select id="selectListMap" parameterType="java.lang.String" resultType="java.util.HashMap">

MNIST資料輸出識別準確率用到的函式方法

MNIST資料集輸出識別準確率 MINST資料集: 提供6w張28*28畫素點的0~9手寫數字圖片和標籤,用於訓練; 提供1w張2828畫素點的0~9手寫數字圖片和標籤,用於測試。 每張圖片的784個畫素點(2828=784)組成長度為784的一維陣列,作為輸

php 提取返回資料,後面程式碼繼續執行封裝函式

使用者登入後,記錄使用者登入日誌,傳送登入通知等邏輯不需要使用者等待等場景,可以先返回資料更使用者, 後面登入日誌等返回資料後再執行 提示:nginx和Apache提前返回資料不一樣詳見函式內部程式碼 使用方法: $data =‘hello world!’;

利用softmax函式對mnist資料簡單分類

mnist資料集的特點 每一張圖片包含28**28個畫素,我們把這一個陣列展開成一個向量,長度是28*28=784。因此在 MNIST訓練資料集中mnist.train.images 是一個形狀為 [60000, 784] 的張量,第一個維度數字用 來索引圖片

ORACLE隨機從表中取一條資料作為函式返回

需求是這樣的:有一張經緯度表,需要從中隨機取一條資料插入另一張表作為其中的兩個欄位。插入過程在儲存過程中,所以需要函式返回值為經緯度資料物件。 首先,生成返回值物件POINT_OBJECT,包括經度緯度。 --生成經緯度 CREATE OR REPLACE TYPE POINT_OBJECT AS OB

Flask04 後臺獲取請求資料、檢視函式返回型別、前臺接受響應資料

1 後臺獲取請求資料   1.1 提出問題     前臺傳送請求的方式有哪些     後臺如何獲取這些請求的引數   1.2 前臺傳送請求的方式     GET、POST、AJAX     點睛:如果不指定請求方式,瀏覽器預設使用GET請求     點睛:進入登入頁面的請求

PostgreSql對空間資料的操作函式

  GIS開發對資料的操作,主要是對空間資料的操作。PostgreSql提供了一些處理空間資料的函式,操作起來是比較方便的。下面就記錄一下,最近做專案裡面用到的一些,也是比較常用的。 空間資料  

獲取webservice 返回的 dataset 資料 並轉換成 datatable

 Service1 service= new Service1(); DataTable dt = service.Get_Data(prods_no.Text.Trim()).Tables[0];             total_pack_amt.Text

plsql返回記錄的方法利用table()函式—之二

今天在開發的時候,要找出兩個表中的不同記錄。我一般是用exists的,但看到也可以這樣 SELECT T5,T6,T7,T8 FROM TAB02 WHERE      T5||T6||T7 NOT IN      (SELECT T1||T2||T3 FROM TAB01)

【python 】資料型別和返回資料型別的函式

字串+字串 →稱為 "拼接"   數字+數字 →稱為"加法運算" 一、資料型別:整型、浮點型、布林型別 1、整型:整數 注意:python2中長整型需要在後面加l,python3中不區分整型和長整