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文檔。
 ***************************************************/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章