stored-procedures - 计数在存储过程中给出错误的结果
问题描述
我从存储过程中运行的查询中得到不正确的计数。当我们运行相同的查询(在硬编码表名和模式名的值之后)它会给出正确的结果。
初步分析表明,在存储过程中运行的查询由于某种原因忽略了第二个过滤器(即 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
我猜 -
所以这暗示,也许在存储过程中,第二个过滤条件被忽略了。
除了帮我解决其他问题,请帮我找出这个异常背后的原因。
提前致谢。
解决方案
我认为您的问题在于 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)工作
推荐阅读
- node.js - 使用 Mongoose 分组
- python - Pandas 将一系列值分配给特定位置的最有效方法
- android - Android 8 System App 更新仅在重启后生效
- mysql - 为什么并发的“删除...插入”语句会导致死锁?
- html - 一种形式的多个按钮
- php - PDO Sqlite 中的查询比命令行 Sqlite3 客户端慢
- docker - Kubernetes:为 docker 提供参数
- mysql - SQL 分组列
- python - 如何提取不在标签内的2个不同的封闭html标签之间的文本?
- javascript - 禁用按钮,在另一个按钮时钟后启用按钮