本帖最后由 万望 于 2016-1-17 15:56 编辑
在ORACLE中,要获得日期中的年份,例如把sysdate中的年份取出来,并不是一件难事。常用的方法是:Selectto_number(to_char(sysdate,'yyyy')) from dual,而实际上,oracle本身有更好的方法,那就是使用Extract函数,使用方法是:Select Extract(year fromsysdate) from dual,此方法获得的结果,是数值型的,这种方法省掉了类型转换,更加简洁。
相应的,要取得月份或日,可以用select extract (month from sysdate) from dual和select extract (day from sysdate) from dual。 Oracle EXTRACT函数 EXTRACT内置函数,可以处理DATATIME和INTERVAL,并从中返回各部分信息,如从TIMESTAMP返回时区,从INTERVAL返回小时/天/分钟
语法如下:
EXTRACT(YEAR|MONTH|DAY|HOUR|MINUTE|SECOND|TIMEZONE_HOUR|TIMEZONE_MINUTE|TIMEZONE_REGION|TIMEZONE_ABBRFROM expr)
1、如果返回年或月,FROM后面的expr必须是以下类型: DATE,TIMESTAMP, TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE, orINTERVAL YEAR TO MONTH.
2、如果返回DAY,FROM后面的expr必须是以下类型:
DATE, TIMESTAMP, TIMESTAMP WITHTIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE, or INTERVAL DAY TO SECOND.
3、如果返回时分秒,FROM后面的expr必须是以下类型:
TIMESTAMP, TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE,or INTERVAL DAY TO SECOND.
DATE类型是无效的,因为Oracle数据库把DATA类型处理为ASCI DATE,并无time可用。
4、如果返回TIMEZONE_HOUR, TIMEZONE_MINUTE, TIMEZONE_ABBR,TIMEZONE_REGION, or TIMEZONE_OFFSET,FROM后面的expr必须是以下类型:TIMESTAMP WITH TIME ZONE orTIMESTAMP WITH LOCAL TIME ZONE.
EXTRACT提取的表达式是一个ASCI的日期时间类型,而非Oracle自有的DATE类型,也就是说,只能从DATE类型的数据里面提取年、月、日。 - select hiredate ,
- extract(year from hiredate) as year,
- extract(month from hiredate) as month,
- extract(day from hiredate) as day from emp;
-
- select extract(hour from hiredate) as hour from emp;
- --从date类型的数据里取hour、minute、second会报错。
- SQL> select extract(hour from hiredate) as hour from emp;
- select extract(hour from hiredate) as hour from emp
- *
- ERROR at line 1:
- ORA-30076: invalid extract field for extract source
-
- --timestamp示例
- select dt2-dt1
- from (select to_timestamp('29-feb-2000 01:02:03.122000',
- 'dd-mon-yyyy hh24:mi:ss.ff') dt1,
- to_timestamp('15-mar-2001 11:22:33.000000',
- 'dd-mon-yyyy hh24:mi:ss.ff') dt2
- from dual );
-
- DT2-DT1
- ---------------------------------------------------------------------------
- +000000380 10:20:29.878000000
-
- --返回了380天,10小时,20分钟,29.878秒
- --而用EXTRACT更轻松
- select extract(day from dt2 - dt1) day,
- extract(hour from dt2 - dt1) hour,
- extract(minute from dt2 - dt1) minute,
- extract(second from dt2 - dt1) second
- from (select to_timestamp('29-feb-2000 01:02:03.122000',
- 'dd-mon-yyyy hh24:mi:ss.ff') dt1,
- to_timestamp('15-mar-2001 11:22:33.000000',
- 'dd-mon-yyyy hh24:mi:ss.ff') dt2
- from dual);
-
- DAY HOUR MINUTE SECOND
- ---------- ---------- ---------- ----------
- 380 10 20 29.878
复制代码因此这就为从日期类型的数据中抽取部分数据又多了一种选择: - SQL> select extract(year from sysdate) from dual;
-
- EXTRACT(YEARFROMSYSDATE)
- ------------------------
- 2014
-
- SQL> select to_char(sysdate,'yyyy') from dual;
-
- TO_C
- ----
- 2014
-
- SQL> select to_char(sysdate,'YEAR') from dual;
-
- TO_CHAR(SYSDATE,'YEAR')
- ------------------------------------------
- TWENTY FOURTEEN
复制代码
|