如何形成oracle函数-TIMESTAMP输入-日期数学-数字返回

时间:2018-07-25 10:42:23

标签: oracle sql-function

我正在尝试创建一个使用TIMESTAMP输入的oracle函数,计算该时间戳与今天之间的天数,并返回该数字。我没有正确构建它,也不知道如何解决:

create or replace FUNCTION "DAYSSINCEOPENDATE" (OPENDATE IN TIMESTAMP) 
   RETURN NUMBER
   AS
   retval  NUMBER;

        BEGIN
           SELECT (SYSDATE - CAST(OPENDATE AS DATE) FROM DUAL)) into retval;
           return retval;
        END;

感谢您的帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

正如@Aleksej在评论中所说,the order of your clauses is incorrect;您需要

SELECT SYSDATE - CAST(OPENDATE AS DATE) into retval FROM DUAL;

所以:

create or replace FUNCTION "DAYSSINCEOPENDATE" (OPENDATE IN TIMESTAMP) 
   RETURN NUMBER
   AS
   retval  NUMBER;

        BEGIN
           SELECT SYSDATE - CAST(OPENDATE AS DATE) into retval FROM DUAL;
           return retval;
        END;
/

select DAYSSINCEOPENDATE(timestamp '2018-01-01 12:13:14.5') from dual;

DAYSSINCEOPENDATE(TIMESTAMP'2018-01-0112:13:14.5')
--------------------------------------------------
                                        204.773368

尽管实际上,您实际上不需要retval变量或针对dual的查询;您可以将其简化为

create or replace FUNCTION "DAYSSINCEOPENDATE" (OPENDATE IN TIMESTAMP) 
RETURN NUMBER
AS
BEGIN
   return SYSDATE - CAST(OPENDATE AS DATE);
END;
/

select DAYSSINCEOPENDATE(timestamp '2018-01-01 12:13:14.5') from dual;

DAYSSINCEOPENDATE(TIMESTAMP'2018-01-0112:13:14.5')
--------------------------------------------------
                                        204.773368