*Memos:
For example, you create person
table, then insert 2 rows into it as shown below:
CREATE TABLE person (
id INTEGER,
name VARCHAR(20),
age INTEGER
);
INSERT INTO person (id, name, age)
VALUES (1, 'John', 27), (2, 'David', 32);
Then, you create my_func()
function which returns a named type row(record) with person_row
as shown below:
CREATE FUNCTION my_func()
RETURNS RECORD
AS $$
DECLARE
person_row RECORD; -- Here
BEGIN
SELECT * INTO person_row FROM person WHERE id = 2;
RETURN person_row;
END;
$$ LANGUAGE plpgsql;
Or:
CREATE FUNCTION my_func()
RETURNS RECORD
AS $$
DECLARE
person_row person%ROWTYPE; -- Here
BEGIN
SELECT * INTO person_row FROM person WHERE id = 2;
RETURN person_row;
END;
$$ LANGUAGE plpgsql;
Then, calling my_func()
gets a named type row(record) as shown below:
postgres=# SELECT my_func();
my_func
--------------
(2,David,32)
(1 row)
Now, you can access the element of the named type row(record) with to_json()
, to_jsonb()
and row_to_json()
as shown below:
postgres=# SELECT to_json(my_func())->'id' AS id;
id
----
2
(1 row)
postgres=# SELECT to_jsonb(my_func())->'name' AS name;
name
---------
"David"
(1 row)
postgres=# SELECT row_to_json(my_func())->'age' AS age;
age
-----
32
(1 row)
*Memos:
In addition, you can use trim() to trim "
from "David"
as shown below:
postgres=# SELECT trim(BOTH '"' FROM (to_json(my_func())->'name')::VARCHAR(20)) AS name;
name
-------
David
(1 row)
postgres=# SELECT trim(BOTH '"' FROM (to_jsonb(my_func())->'name')::VARCHAR(20)) AS name;
name
-------
David
(1 row)
postgres=# SELECT trim(BOTH '"' FROM (row_to_json(my_func())->'name')::VARCHAR(20)) AS name;
name
-------
David
(1 row)
*Memos:
select (retrec()).p1;
select t.*, t.p1, t.p2 from retrec() t;
select * from retrec();
– Endogenous