2017-06-29 68 views
0

根據文檔和此tutorial。我可以用;Postgres在「CAST」處或附近的語法錯誤

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"

我試着調換TY從十進制到整數,但我得到同樣的問題。

Postrgres 9.6.2

+0

請顯示您的完整查詢語句。目前,它看起來像你的查詢只是'CAST ...',這是行不通的。這應該至少類似於'SELECT CAST(table.totalvalue AS decimal(12,2))FROM table;'作爲你鏈接的教程解釋。 – dhke

+0

已添加完整查詢 –

+3

也許您在第一列('totalvalue')後忘記了逗號。嘗試:'SELECT totalvalue, CAST(table.totalvalue AS decimal(12,2))FROM table;' –

回答

1

我想你是誤會的CAST目的。調用CAST不會更改列的類型,但僅在SELECT時刻纔會更改它的值。要改變它的類型,你必須以ALTER COLUMN結合CAST

--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; 
0

刪除totalvalueCAST(..)之前說,它應該工作:

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

我也希望你沒有使用table爲您的表的名稱,因爲它是SQL關鍵字。如果你這樣做,那麼總是雙引號:

SELECT 
    CAST ("table".totalvalue AS decimal(12,2)) 
FROM "table"; 
相關問題