PG中的幾種數據類型轉換方式
1、通過格式化函數進行轉換
函數 | 返回類型 | 描述 | 示例 |
to_char(timestamp,text) | text | 把時間戳轉換成字符串 | to_char(current_timestamp,‘HH12:MI:SS’) |
to_char(interval,text) | text | 把間隔轉換成字符串 | to_char(interval ‘15h 2m 12s’,'HH24:MI:SS) |
to_char(int,text) | text | 把整數轉換成字符串 | to_char(125,'999) |
to_char(numeric,text) | text | 把數字轉換成字符串 | to_char(-125.8,‘999D99S’) |
to_date(text,text) | date | 把字符串轉換成日期 | to_date(‘05 Dec 2000’,‘DD Mon YYYY’) |
to_number(text,text) | numeric | 把字符串轉換成數字 | to_number(‘12,454.8-’,'99G999D9S) |
to_timestamp(text,text) | timestamp | 把字符串轉換成時間戳 | to_timestamp(‘05 Dec 2000’,‘DD Mon YYYY’) |
2、使用cast函數進行轉換
將varchar字符串轉換成text類型:
將varchar字符類型轉換成int4類型:
3、通過::操作符進行轉換
示例:
「PostgreSQL」PostgreSQL數據類型格式轉換
比如有表student:
name (VARCHAR) | sex (VARCHAR) | id (VARCHAR) |
張三 | 男 | 1001 |
李四 | 男 | 1002 |
小紅 | 女 | 1003 |
我想查詢學號(id)為20的學生的名字:
可能報錯 No operator matches the given name and argument type(s). You might need to add explicit type casts.
很明顯, id 列是 VARCHAR 類型, 但是查詢語句的類型為 數字類型, 此時我們就要進行數據格式轉換:
以下有幾種方式:
CAST( 字段 AS 你要轉換為的數據類型 )
字段 :: 你要轉換為的數據類型