简体   繁体   English

PostgreSQL函数返回记录数

[英]Postgresql function returning number of records

I would like to create a function returning the number of records that an SQL expression passed as parameter can generate. 我想创建一个函数,该函数返回作为参数传递的SQL表达式可以生成的记录数。 Can anyone put me on the right path? 谁能把我放在正确的道路上?

In plain SQL you can get the number of returned rows using a derived table (placing the query in a subquery in the FROM clause) like this: 在普通SQL中,您可以使用派生表(将查询放在FROM子句中的子查询中)来获取返回的行数,如下所示:

select count(*)
from (
    <your query>
    ) s;

Do the same in a plpgsql function. 在plpgsql函数中执行相同的操作。 You need a dynamic command as the function should work for any valid SQL query: 您需要一个动态命令,因为该函数适用于任何有效的SQL查询:

create or replace function number_of_rows(query text)
returns bigint language plpgsql as $$
declare
    c bigint;
begin
    execute format('select count(*) from (%s) s', query) into c;
    return c;
end $$;

Example: 例:

select number_of_rows('select * from generate_series(1, 3)');

 number_of_rows 
----------------
              3
(1 row) 

Your function should return a SETOF some (record) type. 您的函数应该返回SETOF一些(记录)类型。 You then use the RETURN NEXT syntax to return each row. 然后,您可以使用RETURN NEXT语法返回每一行。

See the example in the doc page for this. 为此,请参见文档页面中的示例。 https://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#id-1.8.8.8.3.4 https://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#id-1.8.8.8.3.4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM