如何实现获取整行的PostgreSQL函数?

如何实现获取整行的PostgreSQL函数?,postgresql,plpython,Postgresql,Plpython,例如,我想计算表中每一行的空字段数 我应该使用什么参数类型声明 我尝试了复合类型(表名作为类型): 但如果我这样称呼它,它与参数类型不匹配: SELECT count_null(*) FROM my_table; 假设您使用的是Postgres>=9.3,您可以通过json转换来实现这一点,如下所示: create or replace function count_null( _r json ) returns integer as $$ select cou

例如,我想计算表中每一行的空字段数

我应该使用什么参数类型声明

我尝试了复合类型(表名作为类型):

但如果我这样称呼它,它与参数类型不匹配:

SELECT count_null(*) FROM my_table;

假设您使用的是Postgres>=9.3,您可以通过json转换来实现这一点,如下所示:

create or replace function count_null(
    _r json
) returns integer as $$
    select
        count(1)::integer
    from
        (
            select
                row_to_json(json_each(_r)) as condensed_record
        ) as __base
    where
        condensed_record->>'value' is null;
$$ language sql immutable;

---------

select
    count_null(row_to_json(my_table))
from
    my_table;
这还有使用SQL语言而不是plpythonu语言的额外好处,因此查询规划器可以在一定程度上对其进行优化

create or replace function count_null(
    _r json
) returns integer as $$
    select
        count(1)::integer
    from
        (
            select
                row_to_json(json_each(_r)) as condensed_record
        ) as __base
    where
        condensed_record->>'value' is null;
$$ language sql immutable;

---------

select
    count_null(row_to_json(my_table))
from
    my_table;