PL/pgSQL 函数:如何使用执行语句返回具有多列的普通表 [英] PL/pgSQL functions: How to return a normal table with multiple columns using an execute statement
本文介绍了PL/pgSQL 函数:如何使用执行语句返回具有多列的普通表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个 PL/pgSQL 函数,它必须返回一些用户信息.
I've got this PL/pgSQL function which must return some users information.
CREATE OR REPLACE FUNCTION my_function(
user_id integer
) RETURNS TABLE(
id integer,
firstname character varying,
lastname character varying
) AS $$
DECLARE
ids character varying;
BEGIN
ids := '';
--Some code which build the ids string, not interesting for this issue
RETURN QUERY
EXECUTE 'SELECT
users.id,
users.firstname,
users.lastname
FROM public.users
WHERE ids IN (' || ids || ')';
END;
$$ LANGUAGE plpgsql;
我面临的问题是函数的结果是这样的单列表:
The problem I'm facing is that the result of the function is a single columns table like this:
╔═══╦═════════════════════╗
║ ║my_function ║
╠═══╬═════════════════════╣
║ 1 ║ (106,Ned,STARK) ║
║ 2 ║ (130,Rob,STARK) ║
╚═══╩═════════════════════╝
虽然我期望:
╔═══╦════════════╦════════════╦═════════════╗
║ ║ id ║ firstname ║ lastname ║
╠═══╬════════════╬════════════╬═════════════╣
║ 1 ║ 106 ║ Ned ║ STARK ║
║ 2 ║ 103 ║ Rob ║ STARK ║
╚═══╩════════════╩════════════╩═════════════╝
我认为(但不确定)问题来自 EXECUTE
语句,但我不知道如何做.
I think (but not sure) the problem comes from the EXECUTE
statement, but I can't see how to do otherwise.
有什么想法吗?
推荐答案
你是如何执行那个函数的?它用作选择语句.
How are you executing that function? It works as a select statement.
创建一个表:public.users
create table public.users (id int, firstname varchar, lastname varchar);
插入一些记录:
insert into public.users values (1, 'aaa','bbb'),(2,'ccc','ddd');
函数:my_function
CREATE OR REPLACE FUNCTION my_function(user_id integer) RETURNS TABLE(id integer, firstname character varying, lastname character varying) AS $$
DECLARE
ids INTEGER[];
BEGIN
ids := ARRAY[1,2];
RETURN QUERY
SELECT users.id, users.firstname, users.lastname
FROM public.users
WHERE users.id = ANY(ids);
END;
$$ LANGUAGE plpgsql;
现在你可以使用 *
select * from my_function(1);
查询结果
id | firstname | lastname
----+-----------+----------
1 | aaa | bbb
2 | ccc | ddd
或者也有列名
select id,firstname,lastname from my_function(1);
结果
id | firstname | lastname
----+-----------+----------
1 | aaa | bbb
2 | ccc | ddd
这篇关于PL/pgSQL 函数:如何使用执行语句返回具有多列的普通表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文