ANSI Casting Timestamp Netezza - 从Teradata转换SQL

时间:2011-12-06 06:58:37

标签: sql casting teradata netezza ansi-sql

我目前不知道ANSI等效于Teradata FORMAT关键字,用于将时间戳,日期数据类型转换为我们所需的表示格式。我知道这可以用to_char,to_date来完成,就像个别数据库特定的函数一样,但是我想用ANSI编写,以便将来我可以轻松地将代码从一个DB运行到另一个DB。下面是我试图转换为ANSI的当前Teradata SQL,以便我可以在Teradata,Netezza和Vertica等上运行它。

SELECT
CAST( (MYTIME ( FORMAT 'DDMMYYYY')) AS CHAR( 8 ))         
|| CAST( (MYTIME (FORMAT 'HHMISS'))   AS CHAR(6))          
|| CAST(CAST(MYNUMBER  AS FORMAT'-9(5)') AS CHAR(5))             
FROM MYTABLE
;

目前我不知道如何将FORMAT'HHMISS',FORMAT'-9(5)'翻译成ANSI。是否有任何关于这种可能的ANSI等效功能的文档?请帮忙。

2 个答案:

答案 0 :(得分:1)

您可以尝试EXTRACT()函数。 YMMV,但大多数现代RDBMS都支持它。这里真的没有什么好的答案 - 每个DBMS都会以不同的方式处理“日期格式化”问题。

select 
case when extract(day from current_timestamp) < 10 then '0' else '' end || cast(extract(day from current_timestamp) as varchar(2)) ||
case when extract(month from current_timestamp) < 10 then '0' else '' end || cast(extract(month from current_timestamp) as varchar(2)) ||
cast(extract(year from current_timestamp) as varchar(4)) ||
case when extract(hour from current_timestamp) < 10 then '0' else '' end || cast(extract(hour from current_timestamp) as varchar(2)) ||
case when extract(minute from current_timestamp) < 10 then '0' else '' end || cast(extract(minute from current_timestamp) as varchar(2)) ||
case when extract(second from current_timestamp) < 10 then '0' else '' end || cast(extract(second from current_timestamp) as varchar(2)) 

答案 1 :(得分:0)

在Teradata中,您应该能够执行以下操作:

/* The double cast is to truncate any time value associated with MyTime */
SELECT CAST(CAST(MyTime AS DATE) AS TIMESTAMP(6)) 
     + ((MyTime - TIME '00:00:00') HOUR to SECOND(6)) AS MyTimeStamp_
  FROM MyTable;

尝试的另一种选择:

SELECT CreateTimeStamp
     , CAST((CreateTimeStamp (TIMESTAMP(6), FORMAT 'DDMMYYYYBHHMISS.S(6)')) AS CHAR(22)) AS MyTimeStamp_
     , CAST((CreateTimeStamp (TIMESTAMP(6), FORMAT 'DD-MM-YYYYBHH:MI:SS.S(6)')) AS CHAR(26)) AS MyTimeStamp2_
  FROM DBC.Databases
 WHERE DatabaseName = USER;

我的经验是,您必须以不同方式处理每个数据库的日期和时间戳。一种解决方案可能不被普遍接受。但我很想看到在Teradata,Oracle,SQL Server,MySQL等中有效的东西。