【函式】Oracle EXTRACT()函式與to_char() 函式

散葉涔發表於2012-04-23

EXTRACT extracts and returns the value of a specified datetime field from a datetime or interval value expression.
The field you are extracting must be a field of the datetime_value_expr or interval_value_expr. For example, you can extract only YEAR, MONTH, and DAY from a DATE value. Likewise, you can extract TIMEZONE_HOUR and TIMEZONE_MINUTE only from the TIMESTAMP WITH TIME ZONE datatype.
eg.

  • SELECT EXTRACT(YEAR FROM SYSDATE) FROM DUAL; return Current Year
  • SELECT EXTRACT(MONTH FROM SYSDATE) FROM DUAL; return Current Month
  • SELECT EXTRACT(DAY FROM SYSDATE) FROM DUAL; return Current Day
  • SELECT EXTRACT(HOUR FROM SYSDATE) FROM DUAL;Error
Correct:SELECT EXTRACT(HOUR FROM TIMESTAMP '2005-10-10 10:10:10') FROM DUAL;
  • SELECT EXTRACT(MINUTE FROM SYSDATE) FROM DUAL;Error
Correct:SELECT EXTRACT(MINUTE FROM TIMESTAMP '2005-10-10 10:10:10') FROM DUAL;

以上是EXTRACT()函式的使用說明,英文部分有個很重要的部分.就是extract 抽取年月日部分和時分部分的使用方法是不同的.
EXTRACT(YEAR FROM SYSDATE)中FROM 的下一個引數是日期型別的時候可以抽取年月日.就是說這個引數是日期型別的時候就可以抽取年\月\日,而抽取不了時\分部分.抽取時分部分得在FROM 後面加帶TIMESTAMP 且後面加時間字元.
這裡要注意,在(MINUTE FROM TIMESTAMP '2005-10-10 10:10:10')中,如果把'2005-10-10 10:10:10'用日期型別的欄位來代替並轉換成字元型別後,也是錯誤的,估計是這方法的問題.
比如(MINUTE FROM
TIMESTAMP to_date(to_char(日期型別,'YYYY-MM-DD hh24:mi:ss'),'YYYY-MM-DD hh24:mi:ss')),這樣執行不了的.


如果真要從日期型別的欄位中抽取時\分部分用to_char() 函式就可以了.比如to_char(日期型別,'hh24:mi')

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/26892340/viewspace-722069/,如需轉載,請註明出處,否則將追究法律責任。

相關文章