代码之家  ›  专栏  ›  技术社区  ›  Hiker86

如何在postgres中创建函数,返回作为参数给定的表之间的行数

  •  1
  • Hiker86  · 技术社区  · 6 年前

    我在postgres中使用下面的函数返回期望值时遇到问题,我不确定我做错了什么。

    功能:

    create or replace function check_row_diff(_table_minuend varchar(255), _table_subtrahend varchar(255))
    returns bigint as $$
    declare 
        v_num numeric;
    BEGIN
        execute format ('SELECT
            (select count(*) from %s)
          - (select count(*) from %s) AS Difference', _table_minuend, _table_subtrahend);
    return v_num;
    end;
    $$ language plpgsql;
    

    然后运行select,返回“NULL”

    select check_row_diff('table_1', 'table_2');
    

    使用“perform”语句只会返回一个错误。将其作为SQL查询运行将返回正确的结果。表1(名称模糊化)有4568条记录,表2(名称模糊化)有2284条记录:

    select 
    (select count(*) from table_1)
    - (select count(*) from table_2) as difference
    

    返回2284的计数。我需要这个检查,因为我正在用python编写一个中间件应用程序,它允许我们的系统集成到云SaaS。我使用“工作”表和“黄金”表来确保每天的数据馈送是成功的,并且记录不会丢失,因为这将集成到许多内部系统中。我无法在postgres版本中使用UPSERT/MERGE,因为DB平台是以无服务器设计(第三方管理的底层实例)托管的SaaS云。在更新“黄金”表,然后将数据馈送到下游系统之前,此函数将作为数据验证模块的一部分调用。

    如果您需要有关该问题的更多信息,请告诉我。

    1 回复  |  直到 6 年前
        1
  •  1
  •   klin    6 年前

    的结果 execute() 应使用 into:

    create or replace function check_row_diff(_table_minuend text, _table_subtrahend text)
    returns bigint as $$
    declare 
        v_num numeric;
    begin
        execute format ('select
            (select count(*) from %s)
          - (select count(*) from %s)', _table_minuend, _table_subtrahend)
        into v_num;
        return v_num;
    end;
    $$ language plpgsql;