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;为人:谦逊、激情、博学、审问、慎思、明辨、 笃行
学问:纸上得来终觉浅,绝知此事要躬行
为事:工欲善其事,必先利其器。
态度:道阻且长,行则将至;行而不辍,未来可期
转载请标注出处!










