我有功能
CREATE OR REPLACE FUNCTION "public"."GetSoilCod" (
"cod1" integer = 0,
"cod2" integer = 0,
"cod3" integer = 0,
"cod4" integer = 0,
"cod5" integer = 0,
"cod6" integer = 0,
"cod7" integer = 0
)
RETURNS varchar AS
$body$
declare result varchar;
BEGIN
result = cast($1 as varchar(2)) || '.' ||
cast($2 as varchar(2)) || '.' ||
cast($3 as varchar(2)) || '.' ||
cast($4 as varchar(2)) || '.' ||
cast($5 as varchar(2)) || '.' ||
cast($6 as varchar(2)) || '.' ||
cast($7 as varchar(2));
return trim('.0' from result);
END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100;
当我执行此函数并且一个或多个代码被分成10时,此函数的结果是错误的。
示例:
SELECT * FROM "public"."GetSoilCod"(10, 0, 0, 0, 0, 0, 0);
return: 1
expected: 10
SELECT * FROM "public"."GetSoilCod"(10, 20, 0, 0, 0, 0, 0);
return: 10.2
expected: 10.20
为什么被训练为0(零)?我只想修剪“.0”(点零点)
如果我执行此查询:
SELECT * FROM "public"."GetSoilCod"(10, 20, 0, 0, 0, 0, 1);
all its OK
return & expected is: 10.20.0.0.0.0.1
或:
SELECT * FROM "public"."GetSoilCod"(10, 20, 0, 0, 0, 1, 0);
一切都好。回归&预计是:10.20.0.0.0.1
我的错误在哪里?
答案 0 :(得分:3)
Trim不会将参数视为要删除的单个字符串,它会将其视为无序的字符列表,无论它们从开头,结尾或两者出现的顺序如何,都必须将其删除。
来电trim('.0' from result);
与trim('0.' from result);
相同,都会导致从字符串末尾删除所有0
和.
。
SELECT trim('0.' from '100.00')
'1'
请尝试使用regexp_replace
:
SELECT regexp_replace('100.0.2.0.0.0', '(\\.0)+$', '')
100.0.2