2010-06-27 62 views
2

我有功能的PostgreSQL 8.4,TRIM錯誤

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 

爲什麼最後trimed 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); 

一切都OK。返回&預計爲:10.20.0.0.0.1

我的錯誤在哪裏?

回答

3

修剪不會將參數視爲要移除的單個字符串,而會將其視爲無序的字符列表,無論它們從開始,結束還是從兩者出現的順序,都必須將其刪除。

呼叫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 
+0

TNX很多,馬克! :) – Dumitru 2010-06-27 21:04:30