传递从另一个函数返回的日期值的正确格式

时间:2019-06-24 20:01:11

标签: sql oracle plsql

我正在使用V_SQL作为参数,该参数将SQL查询存储为字符串并接受从另一个函数返回的DATE输入。

Function which is returning date value:
----------------------------------------

FUNCTION RETURN_DATE(V_D DATE) RETURN DATE IS
IS_BUS CHAR(1);
V_CNT NUMBER(5);
V_DT DATE;

BEGIN

    V_DT :=V_D;

    WHILE IS_BUSINESS_DAY(V_DT) = 'N'
        LOOP
            V_DT := V_DT - 1;
        END LOOP;

    IF IS_BUSINESS_DAY(V_DT) = 'Y' THEN
            V_DT := V_DT - 1;
    END IF;

RETURN V_DT;
END RETURN_DATE;

V_SQL := 'SELECT A.ACCOUNT_TYPE, B.FIN_ELEM, A.ORG_UNIT_ID, A.GL_ACCOUNT_ID, B.CMN_COA_ID, B.PROD1, B.PROD2, B.PROD3, ' || 
'SUM(CURRENT_BAL) AS CB_SUM, SUM(AVG_BAL) AS AB_SUM, B.FLAG1 FROM DAILYGL_TEST A, AL_LOOKUP B '||
'WHERE A.GL_ACCOUNT_ID = B.GL_ACCT AND A.AS_OF_DATE =  '|| 
**RETURN_DATE(V_RUN_DATE)** ||
' AND ROWNUM <=15 GROUP BY A.ACCOUNT_TYPE, B.FIN_ELEM, A.ORG_UNIT_ID, A.GL_ACCOUNT_ID,B.CMN_COA_ID, B.PROD1, B.PROD2, B.PROD3, A.AS_OF_DATE, B.FLAG1';

I am getting date returned as '29-AUG-2019' and when it is being supplied to this V_SQL query, it is throwing 'AUG not valid identifier issue'. Also, Date in AS_OF_DATE column is in MM/DD/YYYY format such 09/02/2019 for 02-SEP-2019.

Could you please help me in editing, formatting this code properly so this error can be removed. Let me know what I should change in RETURN_DATE(V_RUN_DATE) while supplying it to V_SQL.


Thanks in advance!

1 个答案:

答案 0 :(得分:0)

调用函数的方式是错误的;它不应连接到主查询,而应嵌入其中。看一下这个简化的示例(第5行是您应注意的)。

SQL> create or replace function return_date (v_d in varchar2)
  2    return date
  3  is
  4  begin
  5    return to_date(v_d, 'dd.mm.yyyy');
  6  end;
  7  /

Function created.

SQL> select ename, hiredate from emp where rownum = 1;

ENAME      HIREDATE
---------- -------------------
SMITH      17.12.1980 00:00:00

SQL> declare
  2    v_sql varchar2(500);
  3    l_row emp%rowtype;
  4  begin
  5    v_sql := q'[select * from emp where hiredate = return_date('&v_run_date') ]' ||
  6             ' and rownum = 1';
  7    dbms_output.put_Line(v_sql);
  8    execute immediate v_sql into l_row;
  9    dbms_output.put_line(l_row.ename);
 10  end;
 11  /
Enter value for v_run_date: 17.12.1980
select * from emp where hiredate = return_date('17.12.1980')  and rownum = 1
SMITH

PL/SQL procedure successfully completed.

SQL>