PostgreSQL
 sql >> Teknologi Basis Data >  >> RDS >> PostgreSQL

Bagaimana cara mengembalikan baris hasil kueri dalam fungsi PostgreSQL?

Cara mendeklarasikan fungsi pengembalian set yang saya ingat saat ini:

--example 1
create or replace function test() returns SETOF RECORD
as $$
begin
    RETURN QUERY SELECT * FROM generate_series(1,100);
end;
$$ language plpgsql;
--test output
select * from test() AS a(b integer)

--example 2
create or replace function test2() returns TABLE (b integer)
as $$
begin
    RETURN QUERY SELECT * FROM generate_series(1,100);
end;
$$ language plpgsql;
--test output
select * from test2()

--example 3
create or replace function test3() returns SETOF RECORD
as $$
declare
  r record;
begin
    FOR r IN SELECT * FROM generate_series(1,100) LOOP
      RETURN NEXT r;
    END LOOP;
end;
$$ language plpgsql;
--test output
select * from test3() AS a(b integer);

--example 4
create or replace function test4() returns setof record
as $$
    SELECT * FROM generate_series(1,100)
$$ language sql;
--test output
select * from test4() AS a(b integer);

--example 5
create or replace function test5() returns setof integer
as $$
begin
    RETURN QUERY SELECT * FROM generate_series(1,100);
end;
$$ language plpgsql;
--test output
select * from test5()

--example 6
create or replace function test6(OUT b integer, OUT c integer) RETURNS SETOF record
as $$
begin
    RETURN QUERY SELECT b.b, b.b+3 AS c FROM generate_series(1,100) AS b(b);
end;
$$ language plpgsql;
--test output
select * from test6()



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. pg_dump:[pengarsip (db)] kueri gagal:ERROR:izin ditolak untuk hubungan tentang

  2. Cara mengatur batas waktu pernyataan untuk eksekusi kueri

  3. SQLAlchemy, isolasi transaksi Serializable dan coba lagi dengan cara Python idiomatik

  4. Peran tidak ada dan tidak dapat membuat database saat menggunakan PostgreSQL

  5. finder_sql tidak mengurai string dengan Rails