我有以下postgresql函数:
CREATE OR REPLACE FUNCTION readMessage(messageFor INT, qid INT = NULL, ctxt INT = NULL, messageFrom INT = NULL, byTimeStamp BOOLEAN = FALSE)
RETURNS SETOF message
AS $$
DECLARE
sql varchar;
BEGIN
sql := 'SELECT * FROM message WHERE (receiver_id IS NULL OR receiver_id = $1)';
IF qid IS NOT NULL THEN
sql := sql || ' AND queue_id = $2';
END IF;
IF ctxt IS NOT NULL THEN
sql := sql || ' AND context = $3';
ELSE
sql := sql || ' AND context IS NULL';
END IF;
IF $4 IS NOT NULL THEN
sql := sql || ' AND sender_id = $4';
END IF;
sql := sql || ' ORDER BY';
IF byTimeStamp THEN
sql := sql || ' arrive_time ASC';
ELSE
sql := sql || ' priority DESC';
END IF;
sql := sql || ' LIMIT 1';
RETURN QUERY EXECUTE sql
USING messageFor, qid, ctxt, messageFrom;
END;
$$
LANGUAGE plpgsql;
现在,上面的函数工作正常,但resultSet不包含列名(例如:一个简单的SELECT语句返回带有列名的结果).我需要能够在Java代码中访问上述函数的结果:
Connection con;
PreparedStatement ps = con.prepareStatement("select readMessage(1, 1, 1, 1, true))";
ResultSet rs = ps.executeQuery();
rs.getInt(<column-name>)
代替
rs.getInt(<column-index>)
更可读的代码.如何修改我的postgresql FUNCTION来实现这个目的?
解决方法:
考虑以下示例:
CREATE TABLE test.child (
id integer,
p_id1 integer,
p_id2 integer
);
CREATE OR REPLACE FUNCTION named_cols()
RETURNS SETOF test.child
AS $$
SELECT 0, 12, 23;
$$LANGUAGE sql;
SELECT named_cols();
named_cols
────────────
(0,12,23)
SELECT * FROM named_cols();
id │ p_id1 │ p_id2
────┼───────┼───────
0 │ 12 │ 23
如果以第一种方式调用该函数,则将返回没有列名的记录.看起来你是在第二个之后 – 你会遇到与任何编程语言相同的行为,而不仅仅是Java.