如何执行执行立即陈述的输出结果

时间:2019-11-14 06:35:55

标签: oracle

从下面的查询中,我得到的输出如下。但是我希望输出结果像输出选择查询一样再次执行并提供结果。 另外,我想从输出的最后一行这样删除UNION ALL

 select A from Table1 Union all
 Select A from table2 Union All
 Select A from table3 Union all
 Select A from table4;

查询:

 SET SERVEROUTPUT ON
 Declare
  v_sql varchar2(500);
  v_sql2 varchar2(500);
 v_prj_id varchar2(4000):='ProjectA,ProjectB,ProjectC,ProjectD';

 BEGIN


 Dbms_Output.Put_Line('v_prj_id='||v_prj_id);
 --
 FOR i IN (SELECT trim(regexp_substr(v_prj_id, '[^,]+', 1, LEVEL)) l
        FROM dual 
        CONNECT BY LEVEL <= regexp_count(v_prj_id, ',') + 1 
       ) LOOP

   v_sql :=  'select '''|| i.l ||''' AS "PRJ_ID", EVENT, email,modified_by,modified from ' || i.l || 
  '.Table UNION ALL';

 Dbms_Output.Put_Line (v_sql);

   --
  END LOOP;
 EXECUTE IMMEDIATE v_sql ;

  v_sql2 :=  RTRIM (v_sql, 'UNION ALL');
 EXECUTE IMMEDIATE v_sql2 ;
  Dbms_Output.Put_Line (v_sql2);

  END;
   / 
Output :
    select 'ProjectA' AS "PRJ_ID", EVENT, email,modified_by,modified from ProjectA.event UNION ALL
    select 'ProjectB' AS "PRJ_ID", EVENT, email,modified_by,modified from ProjectB.event UNION ALL
    select 'ProjectC' AS "PRJ_ID", EVENT, email,modified_by,modified from ProjectC.event UNION ALL
    select 'ProjectD' AS "PRJ_ID", EVENT, email,modified_by,modified from ProjectD.event UNION ALL

2 个答案:

答案 0 :(得分:2)

EXECUTE IMMEDIATE不会为您提供SELECT语句的结果。

来自Oracle Docs

  

如果dynamic_sql_statement是SELECT语句,并且您同时省略了in_clause和bulk_collect_into_clause,则execute_immediate_statement将永远不会执行。

如果您想查看SELECT INTO选择值的结果,则可以使用BULK_COLLECT_INTO_CLAUSE子句或EXECUTE IMMEDIATE并将值分配给某个变量。

单行如下所示

SET SERVEROUTPUT ON
DECLARE
  L_RESULT VARCHAR2(20);
BEGIN
  VSQL:= --YOUR LOGIC
  EXECUTE IMMEDIATE VSQL INTO L_RESULT;
  DBMS_OUTPUT.PUT_LINE(L_RESULT);
END;
/

对于多行

DECLARE
  TYPE T IS TABLE OF MYTABLE.ID%TYPE INDEX BY PLS_INTEGER;
  MYROW T;
BEGIN
  VSQL:= --YOUR LOGIC
 EXECUTE IMMEDIATE VSQL BULK COLLECT INTO MYROW;
 DBMS_OUTPUT.PUT_LINE(MYROW.XXX);
 END;
/

答案 1 :(得分:0)

除了将v_sql与原始字符串连接-

,您所做的所有操作都正确
SET SERVEROUTPUT ON
 Declare
  v_sql varchar2(500);
  v_sql2 varchar2(500);
 v_prj_id varchar2(4000):='ProjectA,ProjectB,ProjectC,ProjectD';

 BEGIN


 Dbms_Output.Put_Line('v_prj_id='||v_prj_id);
 --
 FOR i IN (SELECT trim(regexp_substr(v_prj_id, '[^,]+', 1, LEVEL)) l
        FROM dual 
        CONNECT BY LEVEL <= regexp_count(v_prj_id, ',') + 1 
       ) LOOP

   v_sql := v_sql || ' select '''|| i.l ||''' AS "PRJ_ID", EVENT, email, modified_by, modified from ' || i.l || 
  '.Table UNION ALL';

 Dbms_Output.Put_Line (v_sql);

   --
  END LOOP;
 EXECUTE IMMEDIATE v_sql ;

  v_sql2 :=  RTRIM (v_sql, 'UNION ALL');
 EXECUTE IMMEDIATE v_sql2 ;
  Dbms_Output.Put_Line (v_sql2);

  END;
   /