views:

32

answers:

1

I have function

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; 

When I execute this function and one or more of code is divided to 10, result of this function is wrong.

Examples:

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 

Why is trimed last 0(zero)? I want to trim only ".0" (dot zero)

If I execute this query:

SELECT * FROM "public"."GetSoilCod"(10, 20, 0, 0, 0, 0, 1); 
all its OK 
return & expected is: 10.20.0.0.0.0.1 

or:

SELECT * FROM "public"."GetSoilCod"(10, 20, 0, 0, 0, 1, 0); 

all is OK . Return & expected is: 10.20.0.0.0.1

Where is my mistake?

+2  A: 

Trim doesn't treat the argument as a single string to remove, it treats it as an unordered list of characters all of which must be removed regardless of the order in which they appear from the beginning, end or both.

The call trim('.0' from result); is the same as trim('0.' from result); and both cause the removal of all 0 and . from the end of the string.

SELECT trim('0.' from '100.00')
'1'

Try using regexp_replace instead:

SELECT regexp_replace('100.0.2.0.0.0', '(\\.0)+$', '')
100.0.2
Mark Byers
Tnx a lot, Mark! :)
Dumitru