Postgres语法错误在或附近" CAST"

时间:2017-06-29 17:24:30

标签: postgresql casting

根据文档和tutorial。我可以用;

CAST ( expression AS type );

我有一系列存储为text的值,这些值是货币值(格式为200.00,我想成为decimal,所以我尝试过了;

SELECT totalvalue 
CAST (table.totalvalue AS decimal(12,2))
FROM table;

但这只会在语法

上返回错误

ERROR: syntax error at or near "CAST"

我尝试将类型从十进制交换为整数,但我遇到了同样的问题。

Postrgres 9.6.2

2 个答案:

答案 0 :(得分:1)

我猜你误解了CAST的目的。调用CAST不会更改列的类型,只会更改SELECT时刻的值。要更改其类型,您必须将CASTALTER COLUMN

合并
--Changing type of column using cast operator ::
ALTER TABLE d_voa_record1 
    ALTER COLUMN totalvalue TYPE NUMERIC(12,2) USING (totalvalue::NUMERIC(12,2));

--Changing type of column using cast function
ALTER TABLE d_voa_record1 
    ALTER COLUMN totalvalue TYPE NUMERIC(12,2) 
        USING CAST(totalvalue AS NUMERIC(12,2));

--Just changing returned value of column
SELECT CAST(totalvalue AS NUMERIC(12,2)) AS totalvalue_as_numeric,
    totalvalue AS unchanged_totalvalue FROM d_voa_record1;  

答案 1 :(得分:0)

删除totalvalue之前放置的CAST(..),它应该有效:

SELECT 
  CAST (t1.totalvalue AS decimal(12,2))
FROM t1;

我也希望您没有使用table作为您的表的名称,因为它是SQL关键字。如果你这样做,那么总是双引号:

SELECT 
  CAST ("table".totalvalue AS decimal(12,2))
FROM "table";