I have the following table with two fields:
create table tbl_jtest
(
cola int,
colb varchar(10)
);
Inserting some records:
insert into tbl_jtest values(1,'a');
insert into tbl_jtest values(2,'b');
insert into tbl_jtest values(3,'c');
insert into tbl_jtest values(4,'d');
Function:
CREATE OR REPLACE FUNCTION ufn_jtest1(pcola int)
RETURNS json AS
$$
BEGIN
IF pcola = 1
THEN
RETURN QUERY SELECT to_json(a.cola) FROM tbl_jtest a;
ELSE
RETURN QUERY SELECT to_json(a.colb) FROM tbl_jtest a;
END IF;
END;
$$ LANGUAGE plpgsql;
Error details:
ERROR: cannot use RETURN QUERY in a non-SETOF function LINE 7: RETURN QUERY SELECT to_json(a.cola) FROM tbl_jtest a; ^
I have tried the followings:
Try 1:
PERFORM to_json(a.cola) FROM tbl_jtest a;
Try 2:
RETURN QUERY PERFORM to_json(a.cola) FROM tbl_jtest a;
The simplest way to return JSON is with row_to_json() function. It accepts a row value and returns a JSON value. select row_to_json(words) from words; This will return a single column per row in the words table.
Querying the JSON documentPostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.
To convert this PostgreSQL array into JSON, we can use the array_to_json function.
plpgsql is the name of the language that the function is implemented in. Here, we use this option for PostgreSQL, it Can be SQL, C, internal, or the name of a user-defined procedural language. For backward compatibility, the name can be enclosed by single quotes.
Or are you looking for something like this?
create table tbl_jtest
(
cola int,
colb varchar(10),
colc varchar(10)
);
insert into tbl_jtest values(1,'a','e');
insert into tbl_jtest values(2,'b','f');
insert into tbl_jtest values(3,'c','g');
insert into tbl_jtest values(4,'d','h');
SELECT * FROM tbl_jtest;
CREATE OR REPLACE FUNCTION ufn_jtest1(pcola int)
RETURNS table (j json) AS
$$
BEGIN
IF pcola = 1
THEN
RETURN QUERY SELECT row_to_json(a) FROM (SELECT cola, colb FROM tbl_jtest) a;
ELSE
RETURN QUERY SELECT to_json(a) FROM (SELECT colb, colc FROM tbl_jtest) a;
END IF;
END;
$$ LANGUAGE plpgsql;
Test 1
SELECT ufn_jtest1(1);
Output 1
ufn_jtest1
1 {"cola":1,"colb":"a"}
2 {"cola":2,"colb":"b"}
3 {"cola":3,"colb":"c"}
4 {"cola":4,"colb":"d"}
Test2
SELECT ufn_jtest1(2);
Output2 ufn_jtest1
1 {"colb":"a","colc":"e"}
2 {"colb":"b","colc":"f"}
3 {"colb":"c","colc":"g"}
4 {"colb":"d","colc":"h"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With