Oracle动态SQL多行返回

时间:2018-02-08 03:59:54

标签: oracle plsql dynamic-sql

对Oracle没有太多经验,甚至不确定是否可以这样做。我正在尝试创建动态SQL并执行它,有问题的SQL导致返回多行,每行有3列。我能够很好地创建SQL语句,它是我坚持的执行部分。我正在使用here中的示例,但我收到此错误:

Error report -
ORA-00942: table or view does not exist
ORA-06512: at line 41
00942. 00000 -  "table or view does not exist"

从这段代码:

DECLARE thecount number;
 thesql varchar2(8000);
 suffix VARCHAR2(20);
 finalsql varchar2(8000);
 TYPE results IS TABLE OF EDW_HPM.DYNAMIC_TEMP%ROWTYPE;
 results_tbl results;

  CURSOR c1 is
       select cast(cast(substr(p.TABLE_SUFFIX,2,20) as Number(19))as varchar2(50))  
         from support.data_set_phys p
        where p.name not like '%UPD' and p.name like 'FY%' and p.name like '%Encounters'
        and p.is_active = 1 and p.owner_id in ('001441631324','000001666805')
        and NAME not like '%TEST%' and NAME not like 'old%' and NAME not like '%new%' and
        NAME not like '%NEW%' and name not like '%BACK%' and name not like '%back%'
        and cast(replace(substr(p.name, 1, 4),'FY', '20')as int) between 2018 and
        2018 union
                  select cast(cast(substr(p.TABLE_SUFFIX,2,20) as Number(19))as varchar2(50))
         from support.data_set_phys p
        where p.name not like '%UPD' and p.name like 'EPIC HB %' and p.name like '%Encounters'
        and p.is_active = 1 and p.owner_id in ('001441631324','000001666805')
        and NAME not like '%TEST%' and NAME not like 'old%' and NAME not like '%new%' and
        NAME not like '%NEW%' and name not like '%BACK%' and name not like '%back%'
        and cast(replace(substr(p.name, 9, 4),'FY', '20')as int) between 2018 and
      2018;

BEGIN

   OPEN c1;
   LOOP
      FETCH c1 INTO suffix;
      EXIT WHEN c1%NOTFOUND;
    thesql := thesql ||'SELECT facility_id,patient_type_id ,count(pat_account_no) FROM encounter_' ||suffix|| ' e group by facility_id, patient_type_id union ';
   END LOOP;
   CLOSE c1;

   finalsql :=SUBSTR(thesql,1,length(thesql)-7);

   EXECUTE IMMEDIATE finalsql BULK COLLECT INTO results_tbl; 


END allrows_by;

此行触发的错误:

 EXECUTE IMMEDIATE finalsql BULK COLLECT INTO results_tbl;

我可以确保表EDW_HPM.DYNAMIC_TEMP确实存在,这必定是某种语法错误,或者我正在尝试在Oracle中无法实现的事情。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您的代码比链接的示例复杂得多。驱动查询不仅极其复杂,而且您的动态语句是与生成的表名称的并集。

  

"这必定是某种语法错误,或者我尝试了一些在Oracle中无法实现的事情。"

动态SQL很难,因为它将编译错误转变为运行时错误。

  

"我可以确保表格EDW_HPM.DYNAMIC_TEMP确实存在"

在这种情况下,它可能是生成的表名,它正在向ORA-00942投掷。

这很容易调试:而不是执行语句显示它。

dbms_output.put_line(finalsql);

现在,您可以通过在SQL客户端中运行它来验证该语句,如果您无法立即发现该bloomer。

可能的原因

  • 表格格式错误
  • 生成的SQL汇总了不存在的表的名称
  • 生成的名称引用不同模式的表,并且没有同义词
  • 生成的名称引用表在不同的模式中,有同义词,但您的用户对表没有权限。