我需要在现有的TIMESTAMP WITH TIME ZONE字段中动态添加几天(或几个月)。
select DATED from MY_TABLE where ID = 1165;
给出:
DATED
---------------------------------------------------------------------------
20-FEB-16 04.31.54 AM EUROPE/MOSCOW
我跑的时候:
UPDATE MY_TABLE SET DATED = DATED + 2 WHERE ID = 1165;
它给出了:
DATED
---------------------------------------------------------------------------
22-FEB-16 04.31.54 AM +03:00
那么如何正确添加2天而不是松散时间戳" EUROPE / MOSCOW"
如何以与天相同的方式添加2个月?
答案 0 :(得分:3)
执行DATED = DATED + 2
时,DATED会隐式转换为DATE
值(没有任何时区信息),然后使用当前会话转换回TIMESTAMP WITH TIME ZONE
值时区设置。
尝试
UPDATE MY_TABLE SET DATED = DATED + INTERVAL '2' DAY WHERE ID = 1165;
或
UPDATE MY_TABLE SET DATED = DATED + 2 * INTERVAL '1' DAY WHERE ID = 1165;
或
UPDATE MY_TABLE SET DATED = DATED + NUMTODSINTERVAL(2, 'day') WHERE ID = 1165;
为了增加2个月你可以使用
UPDATE MY_TABLE SET DATED = DATED + INTERVAL '2' MONTH WHERE ID = 1165;
RESP。例如NUMTOYMINTERVAL(2, 'MONTH')
。
答案 1 :(得分:2)
使用INTERVAL
添加月份的问题是,如果在结果月份中没有足够的天数,它会抛出错误:
SELECT TIMESTAMP '2016-01-30 00:00:00.000' AT TIME ZONE 'UTC'
+ INTERVAL '1' MONTH
FROM DUAL;
给出:
ORA-01839: date not valid for month specified
但是,您可以编写一个简单的(ish)函数来进行算术运算:
Oracle安装程序:
CREATE OR REPLACE FUNCTION TS_ADD_MONTHS(
datetime TIMESTAMP WITH TIME ZONE,
months INT
) RETURN TIMESTAMP WITH TIME ZONE DETERMINISTIC
AS
p_tz CONSTANT VARCHAR2(30) := EXTRACT( TIMEZONE_REGION FROM datetime );
p_utc CONSTANT TIMESTAMP := datetime AT TIME ZONE 'UTC';
p_date CONSTANT DATE := TRUNC( p_utc );
BEGIN
RETURN CAST( ADD_MONTHS( p_date, months ) AS TIMESTAMP WITH TIME ZONE ) AT TIME ZONE p_tz + ( p_utc - p_date );
END;
/
SHOW ERRORS;
<强>查询强>:
SELECT TS_ADD_MONTHS(
TIMESTAMP '2016-01-30 12:12:12.012 EST',
1
) AS datetime
FROM DUAL;
<强>输出强>:
DATETIME
--------------------------------
29-FEB-16 12.12.12.012000000 EST