Get data from PostgreSQL function to java

2020-05-06 17:18发布

问题:

I have written a simple function in PostgreSQL database. From my JAVA source code I am calling this function like

SELECT getData('active');

I am getting the data correct but the table header of the dataset is showing my function name (getdata) not userid and username. In this situation how I can get data?

CREATE or REPLACE FUNCTION getData(value text) 
RETURNS  TABLE(
    userid integer,
    username varchar(50)
) AS -- text AS --
$body$
DECLARE
    fullsql TEXT;
    records RECORD;
    exeQuery TEXT;
BEGIN

fullsql:= 'SELECT userid, username from user_index where status='''value'''';

exeQuery := 'SELECT * FROM (' || fullsql || ') AS records';

RETURN QUERY EXECUTE exeQuery;

END
$body$
LANGUAGE plpgsql;

Currently the output is

getdate
--------------
501,alexanda
502,cathie

But I want to output like:

userid  username
------|---------
501,alexanda
502,cathie

i am trying to acheive following:

SELECT usr.username FROM cust_invoice_index as inv
INNER JOIN
(SELECT getdata('active')) as usr ON (usr.userid=inv.userid_edit)

Following query is working fine:

SELECT usr.username FROM cust_invoice_index as inv
INNER JOIN
(SELECT userid, username from user_index where status='active') as usr ON (usr.userid=inv.userid_edit)

回答1:

As your function returns a result set you should be using select * from getdata('active').

Don't put calls to set returning functions into the select list.

SELECT usr.username 
FROM cust_invoice_index as inv
 JOIN (SELECT * FROM getdata('active')) as usr ON usr.userid=inv.userid_edit