【原創】PostgreSQL 返回多個結果集

來源:互聯網
上載者:User

MySQL的預存程序 可以很方便的一次性的返回多個結果集, 但是POSTGRESQL目前不提供這樣的功能。

一個直譯的方法就是用遊標來做,不過也可以把結果集放到數組裡面或者一個大的暫存資料表或者是XML等的格式來輸出。


比如在MySQL裡面可以這樣簡單的寫一個預存程序。


delimiter ||create procedure sp_get_multiple_set1()begin  select * from j1 limit 20;  select * from tmp_2 limit 20;end;||delimiter ;執行下會得到兩個結果集。t_girl--call sp_get_multiple_set1();+------+------+| id   | str1 |+------+------+|    1 | love ||    2 | hate |+------+------+2 rows in set (0.00 sec)+------+---------------+| id   | register_date |+------+---------------+|    1 | 2014-01-18    ||    2 | 2014-01-03    ||    3 | 2014-01-16    |+------+---------------+3 rows in set (0.00 sec)Query OK, 0 rows affected (0.00 sec)t_girl--



在PostgreSQL環境下,來看下下面的函數代碼,只能用遊標來實現,而且還不能在函數裡面返回。


create or replace function sp_get_multiple_set1(IN f_id int,refcursor,refcursor) returns setof refcursoras$ytt$declare r1 alias for $2;               r2 alias for $3;begin   open  r1 for select * from j1 where id =f_id;   return next r1;   open r2 for select * from tmp_2 where id = f_id;   return next r2;end;$ytt$ language plpgsql;


接下來,在一個事務裡面來擷取對應的遊標結果集。


t_girl=# begin;BEGINt_girl=# select * from sp_get_multiple_set1(1,'a'::refcursor,'b'::refcursor); sp_get_multiple_set1---------------------- a b(2 rows)t_girl=# fetch all from a; id | str1----+------  1 | love(1 row)t_girl=# fetch all from b; id | register_date----+---------------  1 | 2013-01-20(1 row)t_girl=# close a;CLOSE CURSORt_girl=# close b;CLOSE CURSORt_girl=# commit;COMMITt_girl=#


如果是是多個結果集,但是每個結果集裡面只有一行資料的話,也可以用OUT參數來實現。


create or replace function sp_get_single_set2(f_id int,IN refcursor,IN refcursor,OUT r3 ytt_j1,OUT r4 ytt_tmp_2) returns  recordas$ytt$declare r1 alias for $2;              r2 alias for $3;begin   open  r1 for select * from j1 where id =f_id;   open r2 for select * from tmp_2 where id = f_id;   loop      fetch r1 into r3;      fetch r2 into r4;      exit when not found;      return;   end loop;   close r1;   close r2;end;$ytt$ language plpgsql;t_girl=# select * from sp_get_multiple_set2(1,'a'::refcursor,'b'::refcursor);    r3    |       r4      ----------+---------------- (1,love) | (1,2013-01-20)(1 row)t_girl=#

如果返回的多個結果集的欄位和類型都一致的話,那就跟單個結果集一樣了。



相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.