How to use materialized view in stored procedure

in my stored procedure I use couple of queries (see the script below). I want to create materialized views to replace these queries. Is it possible to achieve and how to achieve it in my case? thanks in advance
set serveroutput on
DECLARE
  v_cur_tid NUMBER(5):=0;
  v_cur_cs_attendance NUMBER(5):=0;
  v_cur_c_tot_enrolments NUMBER(5):=0;
  v_most_enrolments NUMBER(5):=0;
  v_least_enrolments NUMBER(5):=0;
  v_most_pop_cid NUMBER(5):=0;
  v_least_pop_cid NUMBER(5):=0;
  CURSOR class_cursor IS
select
id,
name,
max_attendees
from
class
where
id in (select distinct(event_id) from trainer_schedule where event_type='c' and is_active='y')
order by id;
BEGIN
DBMS_OUTPUT.PUT_LINE('==================================================================================================================================');
--print the report header
DBMS_OUTPUT.PUT_LINE('Summary Report No.3: Training Class Active Schedules Summary Report');
FOR r_class IN class_cursor LOOP
--print the header or subsection
select sum(enrolments) into v_cur_c_tot_enrolments from class_schedule where class_id = r_class.id;
IF v_most_enrolments < v_cur_c_tot_enrolments OR v_most_enrolments = 0
THEN v_most_enrolments := v_cur_c_tot_enrolments; v_most_pop_cid := r_class.id;
END IF;
IF v_least_enrolments > v_cur_c_tot_enrolments OR v_least_enrolments = 0
THEN v_least_enrolments := v_cur_c_tot_enrolments; v_least_pop_cid := r_class.id;
END IF;
DBMS_OUTPUT.PUT_LINE('******************************************************************************************');
DBMS_OUTPUT.PUT_LINE('CLASS_ID: '  || r_class.id ||'     '|| 'CLASS_NAME: '  || r_class.name ||'     '||'CAPACITY: '  || r_class.max_attendees ||'     '||'TOTAL_ENROLMENTS: '  || v_cur_c_tot_enrolments);
DBMS_OUTPUT.PUT_LINE(rpad('____________', 12) || lpad('____________', 12) || lpad('____________________', 20) || lpad('____________________', 20) || lpad('____________',12) || lpad('____________',12));
DBMS_OUTPUT.PUT_LINE(rpad('SCHEDULE_ID', 12) || lpad('TRAINER_ID',12) || lpad('START_TIME', 20) || lpad('END_TIME',20) || lpad('ENROLMENTS',12) || lpad('ATTENDANCE',12));
DBMS_OUTPUT.PUT_LINE(rpad('____________', 12) || lpad('____________',12) || lpad('____________________', 20) || lpad('____________________', 20) || lpad('____________',12) || lpad('____________',12));
FOR r_cs IN (select id,to_char(start_time,'DD-MM-YYYY HH24:Mi') as start_time, to_char(end_time,'DD-MM-YYYY HH24:Mi') as end_time, enrolments from class_schedule where class_id = r_class.id order by id)
LOOP
select trainer_id into v_cur_tid from trainer_schedule where event_type='c' and event_id = r_cs.id;
select count(training_session.id) into v_cur_cs_attendance
from training_session, class_schedule
where training_session.attended = 'y' and
training_session.type='c'and
to_char(training_session.start_time,'DD-MM-YYYY HH24:Mi') = to_char(class_schedule.start_time,'DD-MM-YYYY HH24:Mi') and
class_schedule.id = r_cs.id;
DBMS_OUTPUT.PUT_LINE(rpad(r_cs.id, 12) || lpad(v_cur_tid,12) || lpad(r_cs.start_time, 20) || lpad(r_cs.end_time,20) || lpad(r_cs.enrolments,12) || lpad(v_cur_cs_attendance,12));
END LOOP;
END LOOP;
DBMS_OUTPUT.PUT_LINE('******************************************************************************************');
DBMS_OUTPUT.PUT_LINE('******************************************************************************************');
DBMS_OUTPUT.PUT_LINE('MOST_POPULAR_CLASS:  '||v_most_pop_cid||'      TOTAL_ENROLMENTS_TO_DATE: '||v_most_enrolments);
DBMS_OUTPUT.PUT_LINE('LEAST_POPULAR_CLASS: '||v_least_pop_cid||'      TOTAL_ENROLMENTS_TO_DATE: '||v_least_enrolments);
DBMS_OUTPUT.PUT_LINE('==================================================================================================================================');
END;
/

Hi,
you could use Dynamic SQL /Execute immediate to run DDL from a stored procedure.
http://download-uk.oracle.com/docs/cd/B10501_01/appdev.920/a96624/11_dynam.htm
Could you please tell why do you want to create a materialized view in stored procedure ?
How frequently you will runt this procedure . It would is better to create a MV once and use it.
thanks

Similar Messages

  • How to use order by in stored procedure base block?

    How to use order by in stored procedure base block? I need to change order by dynamically

    Use SET_BLOCK_PROPERTY('BLOCK_NAME',ORDER_BY,'COLUMN_NAME1, COLUMN_NAME2');

  • ORA-01031 with materialized view in stored procedure

    USER1 has created a materialized view (MV). The MV is owned by USER2. USER1 needs to query the MV from within a stored procedure. How do I avoid the ORA-01031?
    Here's the illustration:
    SQL> show user
    USER is "USER1"
    SQL> CREATE MATERIALIZED VIEW USER2.ROLL
    2 BUILD IMMEDIATE
    3 REFRESH COMPLETE WITH ROWID
    4 ON DEMAND
    5 AS
    6 select * from user2.test_roll;
    Materialized view created.
    SQL> select status,owner,object_name,object_type where OBJECT_TYPE='MATERIALIZED VIEW';
    STATUS OWNER OBJECT_NAME OBJECT_TYPE
    VALID USER2 ROLL MATERIALIZED VIEW
    SQL> select count(*) from user2.roll;
    COUNT(*)
    959485
    SQL> declare
    2 n number;
    3 begin
    4 select count(*)
    5 into n
    6 from user2.roll
    7 where rownum<100;
    8 dbms_output.put_line(n);
    9* end;
    SQL> /
    99
    PL/SQL procedure successfully completed.
    SQL> create procedure test_mv is
    2 n number;
    3 begin
    4 select count(*)
    5 into n
    6 from as400_snpsht.roll
    7 where rownum<100;
    8 dbms_output.put_line(n);
    9 end;
    10 /
    Warning: Procedure created with compilation errors.
    SQL> select text from user_errors where name like 'TEST_MV';
    TEXT
    PL/SQL: ORA-01031: insufficient privileges
    PL/SQL: SQL Statement ignored
    So the point is:
    * Ad hoc sql works on the MV
    * Anonymous pl/sql works on the MV
    * Stored procedure fails compilation with ora-01031
    Any suggestions are appreciated.

    Sorry; In may example 'as400_snpsht' should have been 'USER2' (the owner of the MV). I changed the real user names to USER1, USER2 to make the example clearer but missed that one.
    I meant to say...
    SQL> create procedure test_mv is
    2 n number;
    3 begin
    4 select count(*)
    5 into n
    6 from user2.roll
    7 where rownum<100;
    8 dbms_output.put_line(n);
    9 end;
    10 /
    Warning: Procedure created with compilation errors.
    SQL> select text from user_errors where name like 'TEST_MV';
    TEXT
    PL/SQL: ORA-01031: insufficient privileges
    PL/SQL: SQL Statement ignored

  • Query against materialized view from stored procedure brings back empty row

    I have a stored procedure that runs a query against a materialized view. When I run the query outside the SP it works just fine. When I change the MV to a table name, the SP works. When I change it back to the MV i get an empty row. Any ideas? The code is below:
    PROCEDURE getAuth     (p_naid        IN  NUMBER,
                             p_scope       IN VARCHAR2,
                             o_xml_data    OUT SYS_REFCURSOR
                             ) IS
      BEGIN
        IF p_scope = 'Approved' THEN
          OPEN o_xml_data FOR
            SELECT naid,
                   p_naid,
                   auth_type,
                   xml_data
            FROM some_mv
            WHERE naid = p_naid;   
          RETURN;
          CLOSE o_xml_data;
    ... the rest of the procedure ...

    does procedure contain EXCEPTION handler?
    if so, then remove, delete & eliminate EXCEPTION handler (at least during testing & debugging)

  • How to use optional prompts with stored procedure universe?

    Hi Experts,
    Iu2019m working on stored procedure universe in BO XI 3.0 SP2 FP2.5 with oracle at back end. My requirement is that I have to pass 5 optional prompts in the report and we have to pass these prompts through open document link. Please tell if this can be worked out on stored procedure universe?
    Thanks in advance.

    Hi,
    Try with OpenDoc syntax as follows.
    http://<servername>:<port>/OpenDocument/opendoc/<plat
    formSpecific>?iDocID=****&sIDType=CUID&sType=wid/rpt&lsM/lsS/lsRPROMPTNAME=[V1],[V2]&sDocName=reportname&sRefresh=Y/N
    where
    server name: cms server name
    port: portno
    <platformspecific>=: for java -> openDocument.jsp
                                      for .net -> opendocument.aspx
    idocid,sDocName & cuid -> we can get report properties ( goto info view -> select report -> right click -> properties i.e. doc id, cuid and report name)
    sType -> type of report i.e webi or deski ...
    lsS -> to pass single prompt value
    lsM -> to pass multiplle values to prompt
    lsR -> range of values ....
    Note: Here prompt name should be same as the one which we used in the report. Use + if there is blank space.
    Cheers,
    Suresh Aluri.

  • How to use @jws:sql call Stored Procedure from Workshop

    Is there anyone know how to use @jws tag call Sybase stored procedure within
    Workshop,
    Thanks,

    Anurag,
    Do you know is there any plan to add this feature in future release? and
    when?
    Thanks,
    David
    "Anurag Pareek" <[email protected]> wrote in message
    news:[email protected]..
    David,
    In the current release, we do not support calling stored procedures from a
    database control. You will have to write JDBC code in the JWS file to call
    stored procedures.
    Regards,
    Anurag
    Workshop Support
    "David Yuan" <[email protected]> wrote in message
    news:[email protected]..
    Anurag,
    I know how to use DB connection pool and create a db control with it. In
    fact, we have created a Web Service with the db control using plain SQL
    in
    @jws:sql. However, my question here is how to use @jws tag in Weblogic
    Workshop to create a Web Services based on Sybase stored procedure orany
    Stored Proc not plain SQL.
    Thanks,
    David
    "Anurag Pareek" <[email protected]> wrote in message
    news:[email protected]..
    David,
    You can use a database control to obtain a connection from any JDBC
    Connection Pool configured in the config.xml file. The JDBC Connectionpool
    could be connecting to any database, the database control is
    independent
    of
    that.
    Regards,
    Anurag
    Workshop Support
    "David Yuan" <[email protected]> wrote in message
    news:[email protected]..
    Is there anyone know how to use @jws tag call Sybase stored
    procedure
    within
    Workshop,
    Thanks,

  • How to use DATETIME parameters in stored procedure?

    I can not define a variable or parameters
    with data type of DATETIME
    when I define stored procedure using Developer/2000.
    Does Oracle not support DATETIME?
    null

    Chen Honghua (guest) wrote:
    : I can not define a variable or parameters
    : with data type of DATETIME
    : when I define stored procedure using Developer/2000.
    : Does Oracle not support DATETIME?
    Oracle supports DATETIME data type.
    "DATETIME" data type is stored in "DATE" data type.
    if you want to DEFINE "10-Jan-1998 10:20" :
    declare
    dummy_date date:=to_date('10-jan-1998 10:00','DD-MON-YYYY
    HH24:MI');
    BEGIN
    END;
    null

  • How to use SPOOL in a stored procedure

    Hi,
    I need to SPOOL the out put of a curson into a file. Please help me to do this. But this is not working.
    declare
    SET DEFINE ON;
    DEFINE SPOOL_FILE='chain.lst'
    cursor c1(var_chn_cnt number) is select owner,TABLE_NAME from dba_tables where CHAIN_CNT>var_chn_cnt order by owner;
    begin
    for c1_var in c1(0)
    loop
    DBMS_OUTPUT.ENABLE(1000000);
    SPOOL &SPOOL_FILE
    --Step 1
    DBMS_OUTPUT.PUT_LINE('set echo on;');
    DBMS_OUTPUT.put_line(chr(13));
    DBMS_OUTPUT.PUT_LINE('ANALYZE TABLE '||c1_var.owner||'.'||c1_var.table_name||' LIST CHAINED ROWS;');
    DBMS_OUTPUT.put_line(chr(13));
    --Step 2
    DBMS_OUTPUT.PUT_LINE('CREATE TABLE '||c1_var.owner||'.'||'CHNTEMP_'||c1_var.table_name||' AS SELECT * FROM '||
    c1_var.table_name||' WHERE ROWID IN (SELECT HEAD_ROWID FROM '||c1_var.owner||'.'||
    'CHAINED_ROWS WHERE TABLE_NAME='''||c1_var.table_name||''' and OWNER='''||c1_var.owner||''||');');
    DBMS_OUTPUT.put_line(chr(13));
    --Step 3
    DBMS_OUTPUT.PUT_LINE('DELETE FROM '||c1_var.owner||'.'||c1_var.table_name||' WHERE ROWID IN (SELECT HEAD_ROWID FROM '||
    c1_var.owner||'.'||'CHAINED_ROWS WHERE TABLE_NAME='''||c1_var.table_name||''' and OWNER='''||c1_var.owner||''||';');
    DBMS_OUTPUT.put_line(chr(13));
    --Step 4
    DBMS_OUTPUT.PUT_LINE('DROP TABLE '||c1_var.owner||'.'||'CHNTEMP_'||c1_var.table_name||';');
    DBMS_OUTPUT.put_line(chr(13));
    --Step 5
    DBMS_OUTPUT.put_line('TRUNCATE TABLE '||c1_var.owner||'.'||'CHAINED_ROWS;');
    DBMS_OUTPUT.put_line(chr(13));
    DBMS_OUTPUT.PUT_LINE('set echo off;');
    DBMS_OUTPUT.put_line('-------------------------------------------------------------------------------------------------');
    end loop;
    --EXCEPTION
    --WHEN OTHERS THEN
    -- raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
    end;
    Regards,
    Mat.

    Hi, Mat,
    Sorry, the answer is the same as it was in [your other thread|http://forums.oracle.com/forums/message.jspa?messageID=3610719#3610719].
    You can't start SPOOLing insided PL/SQL.
    Give the SPOOL command before you start PL/SQL, as Alex, Sundar and I showed you.
    If you really do need to do file I/O from within PL/SQL, use util_file instead of dbms_output. With utl_file you can name, open, read, write and close files from PL/SQL. You can have several output files open at once, if you want to. See the [PL/SQL Packages and Types manual|http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28419/u_file.htm#BABGGEDF] for details.

  • How to refresh materialized view by trigger

    hi,
    im having a problem in refreshing materialized view through a trigger.
    CREATE OR REPLACE TRIGGER L_TRG_MARC_TEST
    BEFORE DELETE OR INSERT OR UPDATE ON MARC_BOOK_B_ENG
    BEGIN
    DBMS_MVIEW.REFRESH('TITLE_ENG_MV','C','',TRUE,FALSE,0,0,0,TRUE);
    END;
    Trigger created.
    SQL> DELETE FROM MARC_BOOK_B_ENG;
    DELETE FROM MARC_BOOK_B_ENG
    ERROR at line 1:
    ORA-04092: cannot COMMIT in a trigger
    ORA-06512: at "SYS.DBMS_SNAPSHOT", line 849
    ORA-06512: at "SYS.DBMS_SNAPSHOT", line 832
    ORA-06512: at "LIBQAL1.L_TRG_MARC_TEST", line 2
    ORA-04088: error during execution of trigger 'LIBQAL1.L_TRG_MARC_TEST'
    plz tell me how to refresh materialized view thru trigger,,and what is wrong in above mentioned situation.
    Regards

    DBMS_MVIEW.REFRESH implicitly commits. COMMIT is not permitted in triggers, as you can see, unless you use AUTONOMOUS_TRANSACTION.
    Try
    CREATE OR REPLACE TRIGGER L_TRG_MARC_TEST
    BEFORE DELETE OR INSERT OR UPDATE ON MARC_BOOK_B_ENG
    DECLARE
    PRAGMA AUTONOMOUS_TRANSACTION;
    BEGIN
    DBMS_MVIEW.REFRESH('TITLE_ENG_MV','C','',TRUE,FALSE,0,0,0,TRUE);
    END;

  • How to call a sql server stored procedure from oracle

    Hi all,
    Please anybody tell me how to call a sql server stored procedure from oracle.
    I've made an hsodbc connection and i can do insert, update, fetch data in sql server from oracle. But calling SP gives error. when I tried an SP at oracle that has line like
    "dbo"."CreateReceipt"@hsa
    where CreateReceipt is the SP of sql server and hsa is the DSN, it gives the error that "dbo"."CreateReceipt" should be declared.
    my database version is 10g
    Please help me how can i call it... I need to pass some parameters too to the SP
    thanking you

    hi,
    thank you for the response.
    when i call the sp using DBMS_HS_PASSTHROUGH, without parameters it works successfully, but with parameters it gives the following error
    ORA-28500: connection from ORACLE to a non-Oracle system returned this message:
    [Generic Connectivity Using ODBC][Microsoft][ODBC SQL Server Driver]Invalid parameter number[Microsoft][ODBC SQL Server Driver]Invalid Descriptor Index (SQL State: S1093; SQL Code: 0)
    my code is,
    declare
    c INTEGER;
    nr INTEGER;
    begin
    c := DBMS_HS_PASSTHROUGH.OPEN_CURSOR@hsa;
    DBMS_HS_PASSTHROUGH.PARSE@hsa(c, 'Create_Receipt(?,?)');
    DBMS_HS_PASSTHROUGH.BIND_VARIABLE@hsa(c,1,'abc');
    DBMS_HS_PASSTHROUGH.BIND_VARIABLE@hsa(c,2,'xyz');
    nr:=DBMS_HS_PASSTHROUGH.EXECUTE_NON_QUERY@hsa(c);
    DBMS_HS_PASSTHROUGH.CLOSE_CURSOR@hsa(c);
    end;
    Create_Receipt is the sp which requires two parameters.
    please give me a solution
    thanking you
    sreejith

  • Can rs.last() be used after calling the stored procedure?

    Can rs.last() be used after calling the stored procedure? If yes what should be the CURSOR types?

    Can rs.last() be used after calling the stored
    procedure? If yes what should be the CURSOR types?That would depend on the driver/database.
    And as I said in your other post it is far more efficient to count records by just returning a count rather than a complete collection regardless of how you get to the end.

  • How to find Materialized views in OBIEE

    Hi gurus,
    how to find materialized views which are used in OBIEE?
    Do We see them in view log session after running a report?
    I have a requirement to find MV'S.Do we use MV'S in OBIEE?What is the use of MV?
    Kindly answer me.
    Thanks,
    siva

    Refer
    http://gerardnico.com/wiki/database/oracle/materialized_view

  • Using Copy statement in Stored procedure

    The following statement works in sqlplus session:
    copy from comment/password@servername append amcomment_temp using
    select * from amcomment
    where commentid in(1,2,3,4)
    I want to use this in a stored procedure. There is a long datatype in this table. The
    procedure will not compile. Have tried execute immediate and compiler rejects this statement also.

    'COPY' is a SQL*Plus command, not PL/SQL. This is why the PL/SQL compiler throws it out.

  • How to Use Transient View Objects to Store Session-level Global Variables

    hi
    Please consider section "40.8.5 How to Use Transient View Objects to Store Session-level Global Variables"
    at http://download.oracle.com/docs/cd/E14571_01/web.1111/b31974/bcstatemgmt.htm#ADFFD19610
    Based on this documentation I created the example application
    at http://www.consideringred.com/files/oracle/2010/ProgrammaticalViewObjectAndRollbackApp-v0.01.zip
    It behaves as show in the screencast at http://screencast.com/t/qDvSQCgpvYdd
    Its Application Module has a Transient View Object instance "MyEmployeesContextVOVI", as master for the child View Object instance "EmpInCtxJobVI".
    On rollback the Transient View Object instance keeps its row and attribute values.
    Also when passivation and activation is forced (using jbo.ampool.doampooling=false ) the Transient View Object instance seems to keep its row and attribute values.
    questions:
    - (q1) Why does the expression #{bindings.MyEmployeesContextVOVIIterator.dataControl.transactionDirty} evaluate as true when a Transient View Object instance attribute value is changed (as shown in screencast at http://screencast.com/t/qDvSQCgpvYdd )?
    - (q2) What would be a robust approach to make a Transient View Object instance more self-contained, and manage itself to have only one single row (per instance) at all times (and as such removing the dependency on the Application Module prepareSession() as documented in "5. Create an empty row in the view object when a new user begins using the application module.")?
    many thanks
    Jan Vervecken

    Thanks for your reply Frank.
    q1) Does sample 90 help ? http://blogs.oracle.com/smuenchadf/examples/
    Yes, the sample from Steve Muench does help, "90. Avoiding Dirtying the ADF Model Transaction When Transient Attributes are Set [10.1.3] "
    at http://blogs.oracle.com/smuenchadf/examples/#90
    It does point out a difference in marking transactions dirty by different layers of the framework, "... When any attribute's value is changed through an ADFM binding, the ADFM-layer transaction is marked as dirty. ...".
    This can be illustrate with a small change in the example application
    at http://www.consideringred.com/files/oracle/2010/ProgrammaticalViewObjectAndRollbackApp-v0.02.zip
    It now shows the result of both these expressions on the page ...
    #{bindings.MyEmployeesContextVOVIIterator.dataControl.transactionDirty}
    #{bindings.MyEmployeesContextVOVIIterator.dataControl.dataProvider.transaction.dirty}... where one can be true and the other false respectively.
    See also the screencast at http://screencast.com/t/k8vgNqdKgD
    Similar to the sample from Steve Muench, another modification to the example application introduces MyCustomADFBCDataControl
    at http://www.consideringred.com/files/oracle/2010/ProgrammaticalViewObjectAndRollbackApp-v0.03.zip
    public class MyCustomADFBCDataControl
      extends JUApplication
      @Override
      public void setTransactionModified()
        ApplicationModule vApplicationModule = (ApplicationModule)getDataProvider();
        Transaction vTransaction = vApplicationModule.getTransaction();
        if (vTransaction.isDirty())
          super.setTransactionModified();
    }Resulting in what seems to be more consistent/expected transaction (dirty) information,
    see also the screencast at http://screencast.com/t/756yCs1L1
    Any feedback on why the ADF Model layer is so eager to mark a transaction dirty is always welcome.
    Currently, question (q2) remains.
    regards
    Jan

  • How to use bind variables in this procedure

    Hi Experts,
    How to use bind variables in this procedure for static queries.
    PROCEDURE DELETE_MER_PROC (M_id IN NUMBER)
    IS
    BEGIN
    V_date DATE;
    SELECT PD_DATE INTO v_date FROM PD_MAINTAIN;
        DELETE FROM MER_CLEAR
        WHERE MER_DT < v_date
        AND ID = M_ID;
    COMMIT;
    END;   
    How to use  v_date and m_id as bind variables in this procedure to avoid hard parsing.
    Please help me.
    Thanks.

    976208 wrote:
    How to use  v_date and m_id as bind variables in this procedure to avoid hard parsing.
    You cannot avoid hard parsing - as the 1st time a SQL statement (like the SELECT or DELETE statements in your code) is encountered, it does not reside in the server's Shared Pool, and needs to be added into the pool via a hard parse.
    Bind variables does not prevent hard parsing. Hard parsing happens when the SQL statement (with or without bind variables) is a brand new statement encountered by the server.
    Bind variables enables the same SQL cursor to be reused, by simply changing the bind variable value.
    Not using bind variables means that each SQL statement is unique and not shareable - as the value is hardcoded into the statement and cannot be changed via a bind value. This typically means LOTS of different SQL statements (where the only difference is the changed value in the statement) are created - with each statement being a new statement not seen before in the Shared Pool and needing to be hard parsed.
    One does not design one's code not to be hard parsed. There ALWAYS will be a hard parse in order to get a SQL statement into the Shared Pool. One designs one's code to REUSE cursors in the Shared Pool.

Maybe you are looking for