PostgreSQL : to_number() 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24307100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:30:22  来源:igfitidea点击:

PostgreSQL : to_number() function

postgresqlcasting

提问by wiltomap

I need to cast a CHARACTER VARYING column into a NUMERIC type. The source column contains values like : 9.9 ; 99.9 ; NULL. I use the following SQL instruction :

我需要将 CHARACTER VARYING 列转换为 NUMERIC 类型。源列包含如下值: 9.9 ; 99.9 ; 空值。我使用以下 SQL 指令:

ALTER TABLE test ALTER COLUMN pression TYPE NUMERIC USING to_number(pression, '99.9') ;

I get an error : ? invalid input syntax for type numeric: "" ? (SQL : 22P02)...

我收到一个错误:?数字类型的无效输入语法:“”?(SQL: 22P02)...

Is there a problem with having both 9.9 and 99.9 kinds of values ?

同时拥有 9.9 和 99.9 种值是否有问题?

Thomas

托马斯

采纳答案by Clodoaldo Neto

It is possible to cast a nullto numeric:

可以将 a 转换nullnumeric

select null::numeric;
 numeric 
---------

(1 row)

select to_number(null, '99.9');
 to_number 
-----------

(1 row)

But not an empty string:

但不是空字符串:

select ''::numeric;
ERROR:  invalid input syntax for type numeric: ""
LINE 1: select ''::numeric;

So update the column to null beforealtering it

因此,更改列之前将其更新为 null

update test
set pression = null
where pression = '';

Then alter it

然后改一下

ALTER TABLE test 
ALTER COLUMN pression TYPE NUMERIC USING to_number(pression, '99.9') ;