我在谷歌上搜索了如何在DB2iSeries中将CHAR转换为TIMESTAMP,但运气不佳,你能帮我吗?
例如:20120216
预期结果:2012年2月16日上午12:00:00
我的UDF:
CREATE FUNCTION TEST.CONVERT_TO_TIMESTAMP (VAL CHARACTER VARYING(20))
RETURNS TIMESTAMP
LANGUAGE SQL
SPECIFIC TEST.CONVERT_TO_TIMESTAMP
MODIFIES SQL DATA
CALLED ON NULL INPUT
FENCED
DISALLOW PARALLEL
NO EXTERNAL ACTION
BEGIN ATOMIC
DECLARE SQLCODE INTEGER DEFAULT 0 ;
DECLARE RETCODE INTEGER DEFAULT 0 ;
DECLARE RET TIMESTAMP ;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION , SQLWARNING , NOT FOUND
BEGIN
SET RETCODE = SQLCODE ;
END ;
IF ( VAL IS NOT NULL ) THEN
SET RET = CAST ( VAL AS TIMESTAMP ) ;
ELSE
SET RET = NULL ;
END IF ;
RETURN RET ;
END
GO
--
结果为空:(
有什么建议吗?
谢谢MRizq
为了将值CAST作为时间戳,需要将值格式化为有效日期。'20120216'不完全在那里,它需要破折号:'2012-02-16'。如果你不能让调用者重新格式化输入,你就必须按照以下几行自己做:
cast(date(substr(val,1,4) concat '-'
concat substr(val,5,2) concat '-'
concat substr(val,7,2)) as timestamp)
我知道这已经得到了回答,但下面展示了一种可以说更干净、更直接的方法。
假设要转换的CHAR值为"20140101",则可以执行以下操作之一:
select date('20140101'||'000000') from sysibm.sysdummy1;
或
select timestamp('20140101'||'000000') from sysibm.sysdummy1;
下面是一个更完整的示例,包含更多的函数和转换,演示了从实际(尽管是临时的)表中选择和转换数据:
-- Create a temp table to demonstrate with:
declare global temporary table DateExample (
ID Integer,
RealTSField Timestamp,
DateCharField CHAR(8),
TSCharField CHAR(20)
) with replace;
-- Insert a demo record to work with:
insert into session.DateExample values(1, '2014-01-01 12:30:23.123456', '20140101', '20140101123023123456');
-- Show what's in the table at this point:
select * from session.DateExample;
-- Now show the conversions in action:
select
d.*,
date(DateCharField||'000000') DateFromDateCharField, -- implicit conversion from YYYYMMDD via tacking on HHMISS as '000000' string
timestamp(DateCharField||'000000') TSFromDateCharField, -- implicit conversion from YYYYMMDD via tacking on HHMISS as '000000' string
timestamp(LEFT(TSCharField,14)) TSFromTSCharField, -- implicit conversion does not support fractional seconds hence we must use LEFT()
timestamp_format(TSCharField, 'YYYYMMDDHH24MISSNNNNNN') TSFromCharField_ExplicitFormat --explicit conversion with timestamp_format
from session.DateExample d;
尝试这种方法最简单的方法可能是粘贴到Ops Navigator的"运行SQL脚本"窗口中,将光标放在第一行,然后重复按Ctrl-Y键,依次运行每个语句。