Oracle函数,其中table_name和date作为输入,Number作为输出

时间:2015-10-27 00:36:37

标签: sql oracle function dynamic-sql

我正在尝试测试一个函数,我将表名和日期作为输入传递,并将数字作为返回值。 我只将日期作为绑定变量传递(不能传递table_name)

CREATE OR REPLACE FUNCTION TABLE_TEST (reptable in varchar2, fltdate in varchar2)   RETURN NUMBER

        IS
        day_exists VARCHAR2(5 CHAR);
        BEGIN

    execute immediate
    'Select CASE WHEN max(day_i)  IS NULL THEN ''NO'' ELSE ''YES'' END FROM '|| reptable ||' WHERE 1 IN
                  (SELECT max(day_i)
                  FROM '|| reptable ||'
                  where day_i = 1 and flt_dptr_Date_d = :1)' into day_exists
                  using fltdate
          ;
            IF day_exists = 'YES' THEN
              return 1;
            END IF;

    END TABLE_TEST;        

这就是我测试它的方式

Select TABLE_TEST('FDR_REP', '07/25/2015') from dual;

当我单独测试它时,即当我只传递table_name或仅传递日期时,它正常工作。 但由于某种原因,它显示错误不是有效的月份。我不相信日期有任何问题。

当我刚传递table_name

时,此部分有效
CREATE OR replace FUNCTION TEST_FUNCTION (name_table IN VARCHAR2) RETURN NUMBER

        IS         

          rday NUMBER;                
  BEGIN 
   execute immediate  'select day_i 
                FROM ' || name_table || '
                WHERE day_i = 1 and rownum = 1' into rday;


   return rday;

  END TEST_FUNCTION;

1 个答案:

答案 0 :(得分:1)

首先尝试将您的fltdate转换为日期。这是您的代码的修订版:

  CREATE OR REPLACE FUNCTION TABLE_TEST (reptable in varchar2, fltdate in varchar2)   RETURN NUMBER
  IS
     day_exists VARCHAR2(5 CHAR);
  BEGIN

     execute immediate
     'Select CASE WHEN max(day_i)  IS NULL THEN ''NO'' ELSE ''YES'' END FROM '|| reptable ||' WHERE 1 IN
     (SELECT max(day_i)
     FROM '|| reptable ||'
     where day_i = 1 and flt_dptr_Date_d = TO_DATE(:1,''MM/DD/YYYY''))' into day_exists
     using fltdate
     ;
     IF day_exists = 'YES' THEN
     return 1;
     END IF;

  END TABLE_TEST;