sql - 在 plpgsql 中连接输出

标签 sql postgresql concatenation aggregate-functions plpgsql

我想在串联文本输出中输出以下 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 以减少混淆。
在手册中阅读这些功能:

关于sql - 在 plpgsql 中连接输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15459570/

相关文章:

sql - 选择带别名和不带-oracle 11g 有什么区别

Python复制和连接链表,保持顺序

linux - 使用 Crontab 连接文件输出文本

java - 为什么会出现 SQL 语法错误? - 预计 "identifier"?

sql - 购买 Microsoft SQL Server 2008 网络版

postgresql - 在 postgresql 中触发日期

sql - 从许多表中清除内容的最快方法

在 C 中连接字符串

mysql,更新选择的纬度、经度半径范围内的表

sql - rails 种子 : How to truncate DB table?