我想在串联文本输出中输出以下 plpgsql 函数的结果。
我该怎么办?我想要这样的东西:
output = output + 'new point';
到目前为止我的功能:
DECLARE
descriptions text[];
i text;
counter int := 1;
_r record;
output text;
BEGIN
descriptions = string_to_array(description, ',');
FOREACH i IN ARRAY descriptions
LOOP
FOR _r IN EXECUTE 'select point_id as id, name_of_location as name, description as desc
from information_on_point_of_interest
where description = '''||descriptions[counter]||''''
LOOP
output := output + _r.id || ',' || _r.name || ',' || _r.desc || '|';
END LOOP;
END LOOP;
RETURN output;
END;
output := output + new point
好像不支持?
最佳答案
为什么?
你的函数失败了,因为你没有初始化output
。它开始为 NULL
保持 NULL
因为 NULL ||任何
都会导致.. NULL
。
您还应该使用 concat_ws()
处理串联列中的任何 NULL
值。
正确的解决方案
使用这个简单的 SQL 查询可以更快(并且更正确)地完成您想要实现的目标:
SELECT string_agg(concat_ws(',', point_id, name_of_location, description), '|')
FROM (SELECT unnest(string_to_array(description_list, ',')) AS description) x
JOIN information_on_point_of_interest USING (description);
我将您的描述列表重命名为 description_list
以减少混淆。
在手册中阅读这些功能:
-
unnest()
(PostgreSQL 8.4+) - aggregate function
string_agg()
(PostgreSQL 9.0+) -
concat_ws()
(PostgreSQL 9.1+)
关于sql - 在 plpgsql 中连接输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15459570/