1. 程式人生 > 其它 >PG中的幾種資料型別轉換方式

PG中的幾種資料型別轉換方式

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型別:

select cast(varchar'123' as text);


將varchar字元型別轉換成int4型別:
select cast(varchar'123' as int4);


3、通過::操作符進行轉換


示例:

select 1::int4 2/3::numeric;



「PostgreSQL」PostgreSQL資料型別格式轉換


比如有表student:

name (VARCHAR) sex (VARCHAR) id (VARCHAR)
張三 1001
李四 1002
小紅 1003


我想查詢學號(id)為20的學生的名字:

SELECT
name FROM student WHERE id = 1001;


可能報錯 No operator matches the given name and argument type(s). You might need to add explicit type casts.

很明顯, id 列是 VARCHAR 型別, 但是查詢語句的型別為 數字型別, 此時我們就要進行資料格式轉換:

以下有幾種方式:

CAST( 欄位 AS 你要轉換為的資料型別 )

SELECT name FROM student WHERE id = cast(1003 as VARCHAR);


欄位 :: 你要轉換為的資料型別
SELECT name FROM student WHERE id = 1002 :: VARCHAR;