首页 > 解决方案 > 计数在存储过程中给出错误的结果

问题描述

我从存储过程中运行的查询中得到不正确的计数。当我们运行相同的查询(在硬编码表名和模式名的值之后)它会给出正确的结果。

初步分析表明,在存储过程中运行的查询由于某种原因忽略了第二个过滤器(即 where ... 和 ...,第二部分被忽略)。

CREATE OR REPLACE PROCEDURE dev.gp_count (tablename VARCHAR(256))
AS
$$ DECLARE schema_name VARCHAR(64);

table_name VARCHAR(128);

check_count_1 INT;

check_count_2 INT;

BEGIN 

schema_name:= SPLIT_PART(tablename,'.',1);

table_name:= SPLIT_PART(tablename,'.',2);

check_count_1 := (select count(*) from information_schema.tables where table_schema = schema_name and table_name like '%' + table_name +'%');
raise info 'check_count_1 - %',check_count_1;

end;
$$
language plpgsql;

并将上述程序称为-

call dev.gp_count ('dev.gp_test1');

从存储过程获得的结果是 - 警告:check_count_1 - 925

如果我们在替换表名和模式的值之后运行相同的查询,那么 -

select count(*) from information_schema.tables where table_schema = 'dev' and table_name like '%gp_test1%';

结果 -

count
3

现在进一步调查这个问题 -

从存储过程获得的计数与从此查询获得的计数相同 -

select count(*) from information_schema.tables where table_schema = 'dev';

结果-

count
925

我猜 -

所以这暗示,也许在存储过程中,第二个过滤条件被忽略了。

除了帮我解决其他问题,请帮我找出这个异常背后的原因。

提前致谢。

标签: stored-proceduresamazon-redshift

解决方案


我认为您的问题在于 1)您的字符串连接和 2)table_name用作变量:

check_count_1 := (select count(*) from information_schema.tables where table_schema = schema_name and table_name like '%' + table_name +'%');

PostgreSQL 字符串连接使用||,所以它应该是这样的:

check_count_1 := (select count(*) from information_schema.tables where table_schema = schema_name and table_name like '%' || table_name || '%');

尝试将其更改为如下所示:

CREATE OR REPLACE PROCEDURE gp_count (tablename VARCHAR(256))
AS
$$ DECLARE
schema_name VARCHAR(64);
table_name1 VARCHAR(128);
check_count_1 INT;
check_count_2 INT;

BEGIN 
schema_name:= SPLIT_PART(tablename,'.',1);
table_name1:= SPLIT_PART(tablename,'.',2);

check_count_1 := (select count(*) from information_schema.tables f where table_schema = schema_name and f.table_name like '%' || table_name1 || '%');

raise info 'check_count_1 - %',check_count_1;

end;
$$
language plpgsql;

披露:我为EnterpriseDB (EDB)工作


推荐阅读