PostgreSQL数据库中的数据类型转换

PostgreSQL的数据类型转换(格式化)函数提供了一套非常有效的工具,用于各种数据类型之间的相互转换,可以将日期/时间,integer,floating point,numeric 转换成格式化的字符串以及反过来从格式化的字符串转换成指定的数据类型。但一般最常用的是一下两类:(1)将特定数据类型转换为字符串,因为在程序开发工程中处理的数据是以字符串为主的;(2)i数字(int)转换为字符串。

下面是常用的数据转换函数( 第一个参数是待格式化的值,而第二个是一个定义输出或输出格式的模板):

函数 返回类型 描述 例子
to_char(timestamptext) text 把时间戳转换成字串 to_char(current_timestamp, 'HH12:MI:SS')
to_char(intervaltext) text 把时间间隔转为字串 to_char(interval '15h 2m 12s', 'HH24:MI:SS')
to_char(inttext) text 把整数转换成字串 to_char(125, '999')
to_char(double precisiontext) text 把实数/双精度数转换成字串 to_char(125.8::real, '999D9')
to_char(numerictext) text 把 numeric 转换成字串 to_char(-125.8, '999D99S')
to_date(texttext) date 把字串转换成日期 to_date('05 Dec 2000', 'DD Mon YYYY')
to_timestamp(texttext) timestamp with time zone 把字串转换成时间戳 to_timestamp('05 Dec 2000', 'DD Mon YYYY')
to_timestamp(double precision) timestamp with time zone 把 UNIX 纪元转换成时间戳 to_timestamp(200120400)
to_number(texttext) numeric 把字串转换成 numeric to_number('12,454.8-', '99G999D9S')

上面例子中的第二个参数是要求转换成什么样的格式。对于时间日期和数字都具有不同的模式,下面是常用的模式:

模式 描述
9 带有指定数值位数的值
0 带前导零的值
. (句点) 小数点
, (逗号) 分组(千)分隔符
PR 尖括号内负值
S 带符号的数值(使用区域设置)
L 货币符号(使用区域设置)
D 小数点(使用区域设置)
G 分组分隔符(使用区域设置)
MI 在指明的位置的负号(如果数字 < 0)
PL 在指明的位置的正号(如果数字 > 0)
SG 在指明的位置的正/负号
RN 罗马数字(输入在 1 和 3999 之间)
FM
填充模式(抑制填充空白和零)

具体示例如下:

表达式 结果
to_char(current_timestamp, 'Day, DD  HH12:MI:SS') 'Tuesday  , 06  05:39:18'
to_char(current_timestamp, 'FMDay, FMDD  HH12:MI:SS') 'Tuesday, 6  05:39:18'
to_char(-0.1, '99.99') '  -.10'
to_char(-0.1, 'FM9.99') '-.1'
to_char(0.1, '0.9') ' 0.1'
to_char(12, '9990999.9') '    0012.0'
to_char(12, 'FM9990999.9') '0012.'
to_char(485, '999') ' 485'
to_char(-485, '999') '-485'
to_char(485,'9 9 9') ' 4 8 5'
to_char(1485, '9,999') ' 1,485'
to_char(1485, '9G999') ' 1 485'
to_char(148.5, '999.999') ' 148.500'
to_char(148.5, 'FM999.999') '148.5'
to_char(148.5, 'FM999.990') '148.500'
to_char(148.5, '999D999') ' 148,500'
to_char(3148.5, '9G999D999') ' 3 148,500'
to_char(-485, '999S') '485-'
to_char(-485, '999MI') '485-'
to_char(485, '999MI') '485 '
to_char(485, 'FM999MI') '485'
to_char(485, 'PL999') '+485'
to_char(485, 'SG999') '+485'
to_char(-485, 'SG999') '-485'
to_char(-485, '9SG99') '4-85'
to_char(-485, '999PR') '<485>'
to_char(485, 'L999') 'DM 485
to_char(485, 'RN') '        CDLXXXV'
to_char(485, 'FMRN') 'CDLXXXV'
to_char(5.2, 'FMRN') 'V'
to_char(482, '999th') ' 482nd'
to_char(485, '"Good number:"999') 'Good number: 485'
to_char(485.8, '"Pre:"999" Post:" .999') 'Pre: 485 Post: .800'
to_char(12, '99V999') ' 12000'
to_char(12.4, '99V999') ' 12400'
to_char(12.45, '99V9') ' 125'

/****************************************************
 *注:文中图表来自PostgreSQL文档。
 ***************************************************/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章