CREATE FUNCTION test()
RETURNS my_table AS
$BODY$
DECLARE
q4 my_table;
BEGIN
-- add brackets to get a value
-- select row as one value, as q4 is of the type my_table
-- and limit result to one row
q4 := (SELECT my_table FROM my_table ORDER BY 1 LIMIT 1);
RETURN q4;
END;$BODY$
-- change language to plpgsql
LANGUAGE plpgsql;
- Anda tidak dapat menggunakan variabel di
sql
fungsi, gunakanplpgsql
. - Anda dapat menetapkan nilai tunggal ke variabel, sementara
select query
mengembalikan set baris. - Anda harus memilih satu baris sebagai satu nilai, karena variabelnya bertipe komposit.
Contoh penggunaan loop:
DROP FUNCTION test();
CREATE FUNCTION test()
-- change to SETOF to return set of rows, not a single row
RETURNS SETOF my_table AS
$BODY$
DECLARE
q4 my_table;
BEGIN
FOR q4 in
SELECT * FROM my_table
LOOP
RETURN NEXT q4;
END LOOP;
END;$BODY$
LANGUAGE plpgsql;
SELECT * FROM test();
Baca dokumentasi tentang Kembali Dari Fungsi