如何在 postgres 中创建 returns 作为参数给定的表之间的行数的函数
how to create function in postgres that returns rowcounts between tables given as parameters
我在使用 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,returns"NULL"
select check_row_diff('table_1', 'table_2');
使用 "perform" 语句只是 returns 一个错误。 运行 这作为一个 SQL 查询 returns 正确的结果。 Table_1(名称混淆)有 4,568 条记录,table_2(名称混淆)有 2,284 条记录:
select
(select count(*) from table_1)
- (select count(*) from table_2) as difference
returns 计数为 2,284。我需要这个检查才能工作,因为我正在编写 python 一个中间件应用程序,它允许我们的系统集成到云 SaaS。我正在使用 "working" 表和 "golden" 表来确保每天的数据馈送是成功的并且记录不会丢失,因为这将集成到许多内部系统中。我无法在 postgres 版本中使用 UPSERT/MERGE,因为数据库平台是以无服务器设计(第三方管理的底层实例)托管的 SaaS 云。在更新 "golden" 表并将数据馈送到下游系统之前,将调用此函数作为数据验证模块的一部分。
如果您需要有关此问题的更多信息,请告诉我。
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;
我在使用 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,returns"NULL"
select check_row_diff('table_1', 'table_2');
使用 "perform" 语句只是 returns 一个错误。 运行 这作为一个 SQL 查询 returns 正确的结果。 Table_1(名称混淆)有 4,568 条记录,table_2(名称混淆)有 2,284 条记录:
select
(select count(*) from table_1)
- (select count(*) from table_2) as difference
returns 计数为 2,284。我需要这个检查才能工作,因为我正在编写 python 一个中间件应用程序,它允许我们的系统集成到云 SaaS。我正在使用 "working" 表和 "golden" 表来确保每天的数据馈送是成功的并且记录不会丢失,因为这将集成到许多内部系统中。我无法在 postgres 版本中使用 UPSERT/MERGE,因为数据库平台是以无服务器设计(第三方管理的底层实例)托管的 SaaS 云。在更新 "golden" 表并将数据馈送到下游系统之前,将调用此函数作为数据验证模块的一部分。
如果您需要有关此问题的更多信息,请告诉我。
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;