PostgreSQL 9.3 : Return strings from function

标签 postgresql postgresql-9.3

我有以下称为 pro() 的函数。我想通过联合所有两个 select 语句和产品输出从中返回字符串。

函数:pro()

我的尝试:

create or replace function pro()
returns varchar as

$$

declare
    sql varchar;
    q varchar;
begin
    sql := 'SELECT DISTINCT  CAST(COUNT(ProductNumber) as varchar) ||'' - Count of the product Number '' as Descp
        FROM product
        UNION ALL
        SELECT DISTINCT CAST(COUNT(ProductName) AS varchar) || '' - Count of the product Name '' as Descp
        FROM product';

    raise info '%',sql;

    execute sql into q;

    return q;

end;
$$

language plpgsql;

调用函数:

select pro();

这只返回 select 语句的第一部分:

 ______________________________________
|pro                                   |
|character varying                     |
|______________________________________|
|6 - Count of the product Number       |
|______________________________________|

预期的结果应该是:

 ______________________________________
|pro                                   |
|character varying                     |
|______________________________________|
|6 - Count of the product Number       |
|______________________________________|
|6 - Count of the product Name         |
|______________________________________|

最佳答案

尝试使用这些函数:

使用plpgsql

create or replace function pro1()returns 
table ( 
       descp text
      )
as
$$
begin
    return QUERY execute (
         'SELECT DISTINCT  CAST(COUNT(product) as varchar) ||'' - Count of the product Number '' as Descp
         FROM product
         UNION ALL
         SELECT DISTINCT CAST(COUNT(productid) AS varchar) || '' - Count of the product Name '' as Descp
         FROM product');
end;
$$
language plpgsql;

使用sql

create or replace function pro2() returns table  ( descp text) 
as
$$
  SELECT DISTINCT  CAST(COUNT(product) as varchar) ||' - Count of the product Number ' as Descp
  FROM product
    UNION ALL
  SELECT DISTINCT CAST(COUNT(productid) AS varchar) || ' - Count of the product Name 'as Descp
  FROM product;
$$
language sql;

关于PostgreSQL 9.3 : Return strings from function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28103644/

相关文章:

java - 是否有用于管理 PostgreSQL 数据库的 Java 或 JSP 网络界面?

php - 过滤器不影响 postgreSQL 表

linux - 使用 mysql2pgsql 从 mysql 传输到 postgres 时出现日期时间错误

Postgresql 外部表存在子句

PostgreSQL - 错误 - 无法打开文件 "C:\Insert_postgres.csv"以读取 : No such file or directory

postgresql - macOS 上的 PostgreSQL 日志在哪里?

sql - 如何获取所选日期和前 n 天之间的所有日期列表?

postgresql - 如何动态地将列添加到 PostgreSQL SQL where 子句

database - 生产环境上的 Laravel 4.x 迁移

sql - Postgres - 删除重复记录