如何将varchar字段值转换为整数字段

时间:2014-08-30 11:55:32

标签: postgresql

例如,在表格中,一个字段为character varying,因此如何将character varying转换为Integer类型,我需要获得返回 Integer 数据类型

中的值

数据库:

3 个答案:

答案 0 :(得分:0)

您可以尝试这样:

SELECT NULLIF(your_value, '')::int

或像那样扩展

SELECT CAST(coalesce(column_name, '0') AS integer) as Value
from table_name

答案 1 :(得分:0)

我建议让功能来完成这项工作,即

    CREATE OR REPLACE FUNCTION chartoint(charparam character varying)
    RETURNS integer AS
    $BODY$
    SELECT CASE WHEN trim($1) ~ '[0-9]+' THEN CAST(trim($1) AS integer) ELSE NULL END;
    $BODY$
    LANGUAGE sql IMMUTABLE STRICT

答案 2 :(得分:-1)

SELECT mycolumn::integer FROM mytable WHERE something 

SELECT CASE WHEN mycolumn = NULL THEN NULL ELSE mycolumn :: Integer END
FROM mytable WHERE something