如何使用null或文本值将字段转换为Postgres中的DOUBLE PRECISION?

时间:2017-08-03 08:08:32

标签: postgresql

我想在select查询中将my_field转换为DOUBLE PRECISION。 my_field返回NULL或Text。

我试试这个:

SELECT
cast(my_table.my_field AS DOUBLE PRECISION) AS my_double_field
FROM mytablename my_table;

而且:

CASE
  WHEN (my_table.my_field IS NULL)
   THEN NULL
   ELSE my_table.my_field AS DOUBLE PRECISION)
END AS my_double_field

我收到了错误:

ERROR: invalid input syntax for type double precision: "null"

所以我尝试使用功能:

CREATE FUNCTION casttodouble(VARCHAR) RETURNS DOUBLE PRECISION AS $$
DECLARE
  text_colum text := $1;
BEGIN
  RETURN cast(text_colum AS DOUBLE PRECISION);
END;
$$ LANGUAGE plpgsql;

  SELECT
    CASE
      WHEN (my_table.my_field IS NOT NULL)
        THEN casttodouble(my_table.my_field)
        ELSE NULL
      END AS my_double_field,
  FROM mytablename my_table;

得到了:

ERROR: invalid input syntax for type double precision: "null"
Where: SQL statement "SELECT cast(text_colum AS DOUBLE PRECISION)"
PL/pgSQL function casttodouble(character varying) line 5 at RETURN

编辑:

这并没有失败:

SELECT
cast(NULL AS DOUBLE PRECISION) AS my_double_field
FROM mytablename my_table;

2 个答案:

答案 0 :(得分:1)

您不应将NULL作为"NULL"字符串传递。 NULL应该是NULL值。NULL值。您必须区分"NULL""NULL"。如果你不能,那么你必须先消除CREATE OR REPLACE FUNCTION to_double1(text) RETURNS double precision AS $$ SELECT CASE WHEN upper($1) = 'NULL' THEN NULL ELSE $1::double precision END $$ LANGUAGE sql IMMUTABLE STRICT; 字符串:

NULL

但基本规则是将NULL保留为真实"NULL"而不是字符串IMMUTABLE。这是设计错误。

对于单行函数,最好使用SQL语言而不是PLpgSQL。内联函数评估功能很有可能 - 更快。不要忘记标记STRICTpostgres=# \pset null **** Null display is "****". postgres=# SELECT to_double1('10101.1'); ┌────────────┐ │ to_double1 │ ╞════════════╡ │ 10101.1 │ └────────────┘ (1 row) postgres=# SELECT to_double1(NULL); -- correct ┌────────────┐ │ to_double1 │ ╞════════════╡ │ **** │ └────────────┘ (1 row) postgres=# SELECT to_double1('NULL'); -- should not be ┌────────────┐ │ to_double1 │ ╞════════════╡ │ **** │ └────────────┘ (1 row) 。这些标志可用于查询优化。

foreach ($test_results as $question_result) {
    if($question_result == 1){
        $correct_question =1;
    }
    else
    {
        $correct_question =0;
    }
}

答案 1 :(得分:0)

刚演员。你不需要所有的逻辑,下面我在一个CAST

中投射字符串和null来加倍精度
t=# with c(v) as (values('2.33'),(null),(3.222))
select cast (v as double precision) from c;
   v   
-------
  2.33

 3.222
(3 rows)