oracle 用于处理字段值的本地函数

inkz8wg9  于 2022-11-28  发布在  Oracle
关注(0)|答案(1)|浏览(118)

我需要将一串“日期”转换为ISO8601时间戳,该时间戳位于为每条记录分配的时区中。
我现在的工作是这样的:

TO_CHAR(TO_TIMESTAMP(TO_CHAR(mp.creation_date, 'YYYY-MM-DD HH24:MI:SS')) AT TIME ZONE WL.TIMEZONE_CODE, 'YYYY-MM-DD"T"HH24:MI:SS.ff3TZH:TZM')

这很好,但必须在20多个领域这样做。
所以我想知道是否有可能创建一个本地函数,命名为类似TO_ISO8601(timestamp, time_zone)的东西。

tsm1rwdh

tsm1rwdh1#

如果我没有理解错的话,这就是您现在所拥有的(尽管进行了一些简化,以便避免(不必要的)数据类型转换):

SQL> with
  2  mp (creation_date) as
  3    (select to_date('2022-11-19 10:17:32', 'yyyy-mm-dd hh24:mi:ss') from dual),
  4  wl (timezone_code) as
  5    (select 'Europe/Zagreb' from dual)
  6  select to_char(cast(creation_date as timestamp) at time zone wl.timezone_code,
  7                 'yyyy-mm-dd"T"hh24:mi:ss.ff3TZH:TZM') result
  8  from mp cross join wl;

RESULT
-----------------------------
2022-11-19T10:17:32.000+01:00

如果您建立接受日期值和时区代码的函数:

SQL> create or replace function to_iso8601
  2    (par_value in date, par_time_zone in varchar2)
  3  return varchar2
  4  is
  5  begin
  6    return to_char(cast(par_value as timestamp) at time zone par_time_zone,
  7                 'yyyy-mm-dd"T"hh24:mi:ss.ff3TZH:TZM');
  8  end;
  9  /

Function created.

然后将其用作

SQL> with
  2  mp (creation_date) as
  3    (select to_date('2022-11-19 10:17:32', 'yyyy-mm-dd hh24:mi:ss') from dual),
  4  wl (timezone_code) as
  5    (select 'Europe/Zagreb' from dual)
  6  select to_iso8601(mp.creation_date, wl.timezone_code) as creation_date
  7  from mp cross join wl;

CREATION_DATE
--------------------------------------------------------------------------------
2022-11-19T10:17:32.000+01:00

SQL>

如果你有一个只读访问权限,那么你将不能创建一个函数。但是,CTE(正如你提到的)来拯救!

SQL> with
  2  function to_iso8601
  3    (par_value in date, par_time_zone in varchar2)
  4    return varchar2
  5    is
  6    begin
  7      return to_char(cast(par_value as timestamp) at time zone par_time_zone,
  8                   'yyyy-mm-dd"T"hh24:mi:ss.ff3TZH:TZM');
  9    end;
 10  --
 11  mp (creation_date) as
 12    (select to_date('2022-11-19 10:17:32', 'yyyy-mm-dd hh24:mi:ss') from dual),
 13  wl (timezone_code) as
 14    (select 'Europe/Zagreb' from dual)
 15  select to_iso8601(mp.creation_date, wl.timezone_code) result
 16  from mp cross join wl;
 17  /

RESULT
--------------------------------------------------------------------------------
2022-11-19T10:17:32.000+01:00

SQL>

相关问题