时区转换 - 从表中选择时区并在TO_TIMESTAMP_TZ函数中使用它

时间:2012-08-19 16:12:36

标签: sql oracle oracle-sqldeveloper

我想学习时区转换 我尝试使用此代码进行时区转换

select 
    ( TO_TIMESTAMP_TZ 
         ( TO_CHAR
             ( sysdate, 'YYYY/MM/DD HH24:MI:SS' ) 
             || ' GMT' ,   'YYYY/MM/DD HH24:MI:SS TZR' 
         ) 
    AT TIME ZONE  DECODE
        (1,1,'US/PACIFIC',2,'EUROPE/LONDON',3,'ASIA/TOKYO',4,'ASIA/CALCUTTA');

但是如果我尝试从表中获取时区而不是使用解码语句,我会收到错误

select
    (TO_TIMESTAMP_TZ 
        ( TO_CHAR 
            ( sysdate, 'YYYY/MM/DD HH24:MI:SS' ) 
            || ' GMT' , 'YYYY/MM/DD HH24:MI:SS TZR' 
         ) 
    AT TIME ZONE 
        (select t_zone from table where region_code=1);

请你帮我理解是什么问题。

我甚至尝试new_time()但仍然无法正常工作

1 个答案:

答案 0 :(得分:0)

首先,您发布的查询缺少像FROM这样的FROM dual;子句,因此无论如何都会出错。以下是我的结果 -

SQL> ALTER SESSION SET NLS_DATE_FORMAT='DD-MON-YYYY HH24:MI:SS';

Session altered.

SQL> select TO_TIMESTAMP_TZ (sysdate,'YYYY-MM-DD HH24.MI.SSXFF TZR') from dual;

TO_TIMESTAMP_TZ(SYSDATE,'YYYY-
---------------------------------------------------------------------------
20-AUG-20 12.13.15 PM -05:00

SQL> select from_tz(to_timestamp(sysdate,'DD-MON-YYYY HH24:MI:SS'), 'US/Eastern') 
at time zone 'Turkey' from dual;

FROM_TZ(TO_TIMESTAMP(SYSDATE,'
---------------------------------------------------------------------------
20-AUG-12 08.15.20 PM TURKEY

SQL> create table tzone (tm_zone varchar2(30));
Table created.

SQL> insert into tzone values('Turkey');

SQL> select * from tzone;

TM_ZONE
------------------------------
Turkey

SQL> select from_tz(to_timestamp(sysdate,'DD-MON-YYYY HH24:MI:SS'), 'US/Eastern') at time zone (select tm_zone from tzone) from dual;

FROM_TZ(TO_TIMESTAMP(SYSDATE,'
---------------------------------------------------------------------------
20-AUG-12 08.16.29 PM TURKEY