Dynamic cursors

Hi,
I'm trying to work on dynamic cursors.
When I try to execute the below code, I'm getting the following error.
BEGIN
  DYNAMIC_CURSOR.OPENCURSOR();
END;
exception raised ORA-00932: inconsistent datatypes: expected - got -
  Below is my code:
CREATE OR REPLACE
PACKAGE BODY dynamic_cursor AS
    PROCEDURE dyn_sel (
        tab_name   IN VARCHAR2,
        field_name IN VARCHAR2,
        val        IN VARCHAR2,
        crs        IN OUT t_crs)
    IS
        stmt VARCHAR2(200);
    BEGIN
        stmt := 'select * from '|| tab_name || ' where '|| field_name ||  ' = :1';
        OPEN crs FOR stmt USING val;
    END dyn_sel;
    PROCEDURE openCursor IS
        tc t_crs;
        f1 VARCHAR2(50);
        f2 VARCHAR2(50);
    BEGIN
        dyn_sel ('EMP','JOB','MANAGER', tc);
        LOOP
            FETCH tc INTO f1, f2;
            EXIT WHEN tc%notfound;
            dbms_output.put_line (f2);
        END LOOP;
    EXCEPTION
        WHEN OTHERS THEN
            dbms_output.put_line ('exception raised '||SQLERRM);
    END openCursor;
END dynamic_cursor; -Thanks

The selected columns must match the INTO clause, so you need to exactly fetch two columns as e.g. in
  stmt := 'select ename, job from ' || tab_name || ' where ' || field_name || ' = :1';
....

Similar Messages

  • Dynamic Cursor in a procedure

    Hi,
    I am using 10g and wanted to check if we can use a dynamic cursor in a procedure.
    Following is my code and wanted to see if that can work with every query passed as a parameter.
    example ,
    exec test1 ('select col1, col2, col3 from table1','Two columns Sql')
    exec test1 ('select col1 from table2','one columns Sql')
    exec test1 ('select col1, col2, col3, col4, col5 from table3','Five columns Sql')
    CREATE OR REPLACE procedure test1 (p_sql IN VARCHAR2, p_subject IN VARCHAR2
    is
      v_cu_string       VARCHAR2(2000);
      v_string          VARCHAR2(2000);
      v_sql             VARCHAR2(4000);
      v_head            VARCHAR2(4000);
      v_head_sql        VARCHAR2(4000);
      v_str_sql         VARCHAR2(4000);
          TYPE cv_typ IS REF CURSOR;
          cv cv_typ;
    begin
      v_sql := p_sql;
        OPEN cv FOR v_sql;
           LOOP
             FETCH cv INTO v_cu_string;
             EXIT WHEN cv%NOTFOUND;
            ------ Processing steps
          END LOOP;
          CLOSE cv;
    END;Thanks

    user527060 wrote:
    Following is my code and wanted to see if that can work with every query passed as a parameter.
    Just curious as to why this is an improvement of
    exec test1 ('select col1, col2, col3 from table1','Two columns Sql')
    select col1, col2, col3 from table1And
    exec test1 ('select col1 from table2','one columns Sql')
    select col1 from table2And
    exec test1 ('select col1, col2, col3, col4, col5 from table3','Five columns Sql')
    select col1, col2, col3, col4, col5 from table3It needs more code from you to build, more code for anyone to enter to execute, limits selects to only one table I would guess also comes with less documentation than SQL.
    http://download.oracle.com/docs/cd/E11882_01/server.112/e17118/toc.htm

  • Dynamic cursor definition in PL/SQL

    Is it possible to have dynamic cursor definition in PL/SQL. Like
    using DBMS_SQL for dynamic SQL. If yes, how?

    Assuming I understand your question correctly, you can use a REF
    CURSOR to which you associate a VARCHAR2 which is the query text:
    DECLARE
    TYPE t_cur IS REF CURSOR ; -- define t_cur as a type
    c_cur t_cur ; -- define an actual variable of type t_cur
    r_emp emp%ROWTYPE ; -- PL/SQL record to hold row
    v_query VARCHAR2(2000) := 'SELECT * FROM emp' ; -- the query!
    BEGIN
    OPEN c_cur FOR v_query ; -- v_query could contain any valid query
    FETCH c_cur INTO r_emp ; -- get first row from dataset
    CLOSE c_cur ; -- remember to close the cursor! ;)
    END ;
    HTH

  • Does Declare Dynamic Cursor Support with Order Clause?

    Given a dynamic cursor like
         declare CUR_10 dynamic cursor for SQLSA;
         prepare SQLSA from :ls_SQL;
         open dynamic CUR_10;
         do while TRUE
              fetch CUR_10 into :ls_var1, :ls_var2
         loop
    where ls_SQL is "select COL1, COL2 from TABLE_A order by COL2 desc"
    can I fetch values in the exact DESCENDING order of COL2?

    Hello Ronald,
    Values will be fetched in the way you SQL statement has been defined for your dynamic cursor, so in the descending order.
    I've tested your code with an Oracle connection and it works perfectly.
    Just ensure to add a condition to your DO WHILE statement when the resultset is exhausted:
    DO WHILE TRUE AND SQLCA.SQLCode <> 100
    Kind regards,
    Jacob

  • Report with Dynamic Cursor

    hi forum
    I need your help and I hope you can help me. In my job I need to do a Report, but the function that containts the cursor returns a ref cursor and this ref cursor doesn't return a special format 'cause the cursor that I use is Dynamic so when I try to do the report it is not generated.
    the documentation says that should return something for example
    type vref_cursor is ref cursor[b] return record;
    or
    type vref_cursor is ref cursor return depto%rowtype;
    but if I use this in a dynamic cursor it generates an Error and don't accpet this declaration only the following
    type vref_cursor is ref cursor;
    Do you Know how should I do the report with a dynamic cursor ?
    best regards
    thank's a lot

    That is not possible. From the online help:
    Each ref cursor query is associated with a PL/SQL function that returns a strongly typed ref cursor.

  • Fetching values of Dynamic Cursor

    Hi,
    Can I fetch values of dynamic cursor into a variable(record OR individual)? If yes what will be the type of that record/variable?
    Thanks in Advance!
    Regards
    RK

    bluefrog wrote:
    There is no way in 10g to identify the column data types of the result set of a dynamic ref cursor.
    In 11g one can use ;
    DBMS_SQL.DESCRIBE_COLUMNS (
    c IN INTEGER,
    col_cnt OUT INTEGER,
    desc_t OUT DESC_TAB);when using DBMS_SQL
    P;In 11g you can use a ref cursor and then use the DBMS_SQL package to convert that ref cursor to a DBMS_SQL cursor where you can then describe the columns. The initial query doesn't have to be a DBMS_SQL cursor. In 10g, unfortunately, there is no way to convert the ref cursor to a DBMS_SQL cursor, so dynamic cursors would have to be written as DBMS_SQL cursors initially. Ref cursors are only really suitable for 3rd party tools, such as when passing queries back to .NET or Java applications. Too many people try and use ref cursors inside PL/SQL and then discover why that's not a good idea.
    PL/SQL 101 : Understanding Ref Cursors:-
    PL/SQL 101 : Understanding Ref Cursors

  • Can I create a dynamic cursor in a program unit on oracle form....

    Hello folks,
    can I create a dynamic cursor on client side ( in a program unit on the oracle form), is it possible, I Know how to create it on server side using Ref cursor, but on client side i got this message (can't be created on client side or something like that).... please if someone can help

    > select count(*) from t_comsis
    <p>But when you put that select string into a varchar2 variable, it won't compile. Which makes it hard to create anything "dynamic".
    <p>In Forms, you can create and populate a record group dynamically, which is ok as long as your select will not retrieve too many (more than several hundred) rows.
    <p>Or, your other option is to use the Forms Exec_SQL dynamic sql package.

  • Using a Dynamic cursor

    Hi,
    I have a problem with this code :
    DECLARE
         v_Column_Name           all_tab_columns.column_name%TYPE;      -- variable for TABLE_SQL
         v_data_type           all_tab_columns.data_type%TYPE;      -- variable for CHPS_SQL
         v_Table_Name           user_tables.table_name%type;
         lc$results     VARCHAR2(32767) := null;
         lc$Champ     VARCHAR2(32767) := null;
         lc$Requete     VARCHAR2(32767) := null;
         CURSOR C1 IS
              SELECT table_name FROM user_tables;
    BEGIN
         OPEN C1;
         LOOP
              FETCH C1 INTO V_Table_name;
              EXIT WHEN C1%NOTFOUND;
              DECLARE
                   CURSOR C2 IS
                        select column_name, data_type from all_tab_columns where table_name = V_TABLE_NAME;
              BEGIN
                   lc$results := 'INSERT INTO ' || v_table_name || '(';
                   lc$requete := 'SELECT ' ;
                   lc$Champ := NULL;
                   OPEN C2;
                   LOOP
                        FETCH C2 INTO V_column_name, V_data_type;
                        EXIT WHEN C2%NOTFOUND;
                        if lc$Champ IS NOT NULL then
                             lc$Champ := lc$champ || ',' || v_column_name;
                             lc$requete := lc$requete || ',' || '''''''''' || ',' || v_column_name || ',' || '''''''''';
                        else
                             lc$champ := lc$champ || v_column_name;
                             lc$requete := lc$requete || '''''''''' || ',' || v_column_name || ',' || '''''''''';
                        end if;
                   END LOOP;
                   CLOSE C2;
                   lc$results := lc$results || lc$champ || ') VALUES (';
                   lc$requete := lc$requete || ' FROM ' || v_table_name;
    -- MY PROBLEM BEGIN HERE
                   DECLARE
    *                    TYPE EmpCurTyp IS REF CURSOR;*
    *                    C3     EmpCurTyp;*
    *               BEGIN*
    *                    OPEN C3 FOR lc$requete;*
    *                    lc$champ := NULL;*
    *                    LOOP*
    *                         FETCH C3 INTO lc$champ ;*
    *                         Exit when C3%NOTFOUND ;*
    *                         lc$champ := lc$results || lc$champ || ')';*
    *                         dbms_output.put_line(lc$champ);*
    *                    END LOOP;*
    *                    CLOSE C3;*
    *               END;*
              END;
         END LOOP;
         CLOSE C1;
    END;          
    the error code is : ORA-00932: inconsistent datatypes: expected - got -
    Need help please,
    Thank

    904907 wrote:
    How can I use the dbms_SQL for this code?99% of the time this indicates design issues. You are trying to write "one-size-fits-all" code which by definition will have substantial overhead. Other than that, in general, you need to declare a variable for each data type possibly returned by dynamic SQL. Then use DBMS_SQL.DESCRIBE_COLUMNS to get data types of select list expressions. Fetch a row and then loop from 1 to number of select list expressions where loop body is one giant IF to test select list expression datatype and issue corresponding DBMS_SQL.COLUMN_VALUE into proper data type variable.
    SY.

  • Dynamic Cursor Fields Reference

    Hi,
    We have a requirement, whereby we need to refer the fields dynamically from the
    cursor, which we cannot decide during development time. It will be keep changing
    and need to be decided during run time only.
    In the below example, I have used "name_in" function to do this, it is not allowed
    in PL/SQL and supported only in Oracle*Forms.
    Please suggest what is the best method available for this requirement, can I
    declare a variable using "ROWTYPE" and use that by any method, thank you.
    DECLARE
    v_Primary_Key int;
    v_Result1 number(10);
    v_Result2 number(10);
    v_Result3 number(10);
    v_Result4 number(10);
    v_cntr int;
    CURSOR CR_TMP
    IS
         SELECT PKFLD, F1, F2, F3, F4, F5, F6 FROM TMP1;
    BEGIN
         FOR CF_TMP IN CR_TMP LOOP
              v_Primary_Key := CF_TMP.PKFLD;
              v_Result1 := CF_TMP.F1 + CF_TMP.F2;
              v_Result2 := CF_TMP.F2 + CF_TMP.F3;
              v_Result3 := CF_TMP.F2 + CF_TMP.F3 + CF_TMP.F4;
              FOR v_cntr in 1..5
              LOOP
              v_Result4 := v_Result4 + to_number(name_in('CF_TMP.F' ||
    v_cntr));
              END LOOP;
         INSERT INTO TMP2
         Values(v_Primary_Key, v_Result1, v_Result2, v_Result3, v_Result4);
         END LOOP;
    COMMIT;
    END;
    Regards,
    Deva

    The following example from my book on Oracle Database 11g PL/SQL Programming should help you because it'll work in at least 10g and perhaps 9i:
    DECLARE
    -- Define explicit record structure.
    TYPE title_record IS RECORD
    ( item_title VARCHAR2(60)
    , item_subtitle VARCHAR2(60));
    -- Define dynamic variables.
    title_cursor SYS_REFCURSOR;
    title_row TITLE_RECORD;
    stmt VARCHAR2(2000);
    BEGIN
    -- Set statement.
    stmt := 'SELECT item_title, item_subtitle '
    || 'FROM item '
    || 'WHERE SUBSTR(item_title,1,12) = :input';
    -- Open and read dynamic curosr, then close it.
    OPEN title_cursor FOR stmt USING 'Harry Potter';
    LOOP
    FETCH title_cursor INTO title_row;
    EXIT WHEN title_cursor%NOTFOUND;
    dbms_output.put_line(
    '['||title_row.item_title||']['||title_row.item_subtitle||']');
    END LOOP;
    CLOSE title_cursor;
    END;
    Hope it helps, Michael

  • Semi-dynamic cursor on heterogeneous tables

    I have a list of Microsoft Access databases. They are yearly transaction databases. The tables in each look exactly alike.
    What I need to do is loop through the "list of databases" (which I retrieve from a secondary source), and loop through table T1 in each of these databases. I could use the completely-dynamic code at AskTom, but I'm guessing that's going to have horrible performance. In my case,I know what the columns are. The only thing that's changing is the link to the database itself. So here's what I want to do:
    Declare a generic cursor C1 (but without linking to any particular database's rowtype).
    Loop through all database link names:
    set C1 = 'select * from T1@' || linked_db_name;
    for rec_c1 in C1 loop
    dbms_output.put_line(rec_c1.field1);
    dbms_output.put_line(rec_c1.field2);
    end loop;
    end loop;
    Is there a way to do this, where I can refer to each field by name? Or must I use the describe and/or have a non-generic cursor as the basis for the cursor definition? My backup option is to drop and recreate the database link each time, with a "reference" DB link created at the outset by the customer. But I don't know if I can do that in PL/SQL (drop and recreate database links).
    Thanks for your assistance!
    Christine Wolak
    SPL Worldgroup, Inc

    Christine:
    I've never actually tried this across a db_link to Access, but it should work.
    DECLARE
       l_sql VARCHAR2(4000);
       l_cur SYS_REFCURSOR;
       TYPE access_rec IS RECORD (col1 VARCHAR2(35),
                                  col2 VARCHAR2(35));
       -- Whatever the appropriate Oracle data type is for the Access field
       -- To do just singleton selects
       l_ar access_rec;
       -- To do bulk collect
       TYPE access_tbl IS TABLE of access_rec INDEX BY BINARY_INTEGER;
       l_at access_tbl;
    BEGIN
       FOR dbs in (SELECT link_name FROM db_table) LOOP
          l_sql := 'SELECT * FROM t1@'||dbs.link_name;
          OPEN l_cur FOR l_sql
    -- For singleton selects
          LOOP
             FETCH l_cur INTO l_ar
             EXIT WHEN l_cur%NOTFOUND;
             << Do whatever here using l_ar.col1, l_ar.col2>>
          END LOOP;     
    -- For bulk collects
          LOOP
             FETCH l_cur BULK COLLECT INTO l_at LIMIT 100
             -- Limit not strictly neccessary, but if ther are a large
             -- number of rows it might be wise.
             FOR i IN 1 .. l_at.COUNT LOOP
                << Do whatever here using l_at(i).col1, l_at(i).col2>>
             END LOOP;
             EXIT WHEN l_cur%NOTFOUND;
             -- Note that the last fetch may retrieve less than LIMIT rows.
             -- it will set NOTFOUND true, so you need to test at the end
             -- of the loop
          END LOOP;
          CLOSE l_cur;  
       END LOOP;
    END;HTH
    John

  • Error in dynamic cursor::

    hi experts
    please help me for this error
    In this code the cursor conditions are not appending to the query
    so when i am executing the result it is displaying the error
    can you help me on this
    SQL> CREATE OR REPLACE PROCEDURE test_dynamic_detailed_rpt (
      2     v_typ             IN       VARCHAR2,
      3     v_initiator   IN       VARCHAR2,
      4     p_rc                  OUT      sys_refcursor
      5  )
      6  IS
      7     v_sql   VARCHAR2(32767);
      8  BEGIN
      9     v_sql := 'SELECT  COUNT(*) FROM  txnlg tl WHERE ';
    10
    11      v_sql := v_sql||'tl.typ = ''1''';
    12
    13
    14           FOR j IN (SELECT tc.tgid, tc.tranid, tc.reqtype
    15                       FROM txnccde tc
    16                      WHERE tc.actstatus = 'Y'
    17                        AND tc.txndesc = v_typ)
    18           LOOP
    19              IF LENGTH (j.tgid) < 4
    20              THEN
    21                 v_sql := v_sql || ' OR ''UP''||J.tgid';
    22                 --'''|| v_typ|| ''')';
    23              ELSE
    24                 v_sql := v_sql || ' OR   J.tgid';
    25              END IF;
    26           END LOOP;
    27
    28     DBMS_OUTPUT.PUT_LINE(v_sql);
    29  END;
    30  /
    Procedure created.
    SQL>
    SQL> set serveroutput on;
    SQL>
    SQL> Var  p_rc refcursor;
    SQL>
    SQL> BEGIN
      2  test_dynamic_detailed_rpt('ALL','C',:p_rc);
      3  END;
      4  /
    SELECT  COUNT(*) FROM  txnlg tl WHERE tl.typ = '1'
    PL/SQL procedure successfully completed.
    SQL>
    SQL> print p_rc;
    ERROR:
    ORA-24338: statement handle not executed
    SP2-0625: Error printing variable "p_rc"
    SQL>

    980560 wrote:
    I have coded that cursor . but the following error is occuring while
    executing the cursor .please help me to resolve this .
    CREATE OR REPLACE PROCEDURE test_dynamic_detailed_rpt (
    v_typ IN VARCHAR2,
    v_initiator IN VARCHAR2,
    p_rc OUT sys_refcursor
    IS
    v_sql VARCHAR2 (32767);
    BEGIN
    v_sql := 'SELECT COUNT(*) FROM txnlg tl WHERE ';
    v_sql := v_sql || 'tl.typ = ''1''';
    FOR j IN (SELECT tc.tgid, tc.tranid, tc.reqtype
    FROM txnccde tc
    WHERE tc.actstatus = 'Y')
    LOOP
    IF LENGTH (j.tagid) < 4
    THEN
    v_sql :=
    v_sql || ' OR ' || 'tl.txntype =' ||''''|| 'AP' ||j.tgid
    || '''';
    ELSE
    v_sql := v_sql || 'OR ' || 'tl.txntype =' ||''''||j.tgid||'''';
    END IF;
    END LOOP;
    DBMS_OUTPUT.put_line (v_sql);
    OPEN p_rc FOR v_sql;
    END;
    Procedure created.
    SQL>
    SQL> set serveroutput on;
    SQL>
    SQL> Var p_rc refcursor;
    SQL>
    SQL> BEGIN
    2 test_dynamic_detailed_rpt('ALL','C',:p_rc);
    3 END;
    4 /
    ORA-06502: PL/SQL: numeric or value error: character string buffer too small
    ORA-06512: at P_DETAILED_REPRT, line 226
    ORA-06512: at line 2
    That error does not relate to the code you've posted. P_DETAILED_REPORT is not the name of your procedure.
    Please post the error you get from running the code shown. I suspect you are trying to build an SQL statement that is too large for the v_sql variable, but we don't have your data to be able to tell.
    I'll repeat what I said earlier:
    Perhaps if you posted some examples of your tables and data, and explained what output you are trying to get, we could help you to write it as a static SQL instead.Read this: {message:id=9360002}
    You'll find that the people who get the quickest answers around here are the ones who ask their questions properly with sufficient information and example data. If you keep people guessing what you want, then they often tend to get bored and go elsewhere.... so the choice is yours... help us to help you.

  • HOW TO CREATE A DYNAMIC CURSOR?

    hi, i have a cursor that i declared it in first_line of my package.
    create or replace package ....
    CURSOR ACCESS_VIEW IS SELECT * FROM SYS.ALL_OBJECTS;
    PROCEDURE PUT...
    FOR REC IN ACCESS_VIEW
    LOOP
    END LOOP;
    in this package and at the first line of 'put' procedure, i will change the ACCES_VIEW CURSOR. how can i do this? pls help me.
    thanx

    in this package and at the first line of 'put' procedure, i will change the ACCES_VIEW CURSOR. how can i do this?
    SQL>  create or replace package pkg
    as
       cursor cur is select * from emp;
       procedure put;
    end pkg;
    Package created.
    SQL>  create or replace package body pkg
    as
       procedure put
       as
       begin
         for c in cur
         loop
            dbms_output.put_line(c.ename);
         end loop;
       end put;
    end pkg;
    Package body created.
    SQL>  exec pkg.put
    SMITH
    ALLEN
    WARD
    JONES
    MARTIN
    BLAKE
    CLARK
    SCOTT
    KING
    TURNER
    ADAMS
    JAMES
    FORD
    MILLER
    PL/SQL procedure successfully completed.
    @Sundar M:
    SQL>  create or replace package pkg
    as
       cur   sys_refcursor;
    end pkg;
    Warning: compiled but with compilation errors
    SQL>  show error
    Errors for PACKAGE PKG
    LINE/COL                                                                       
    ERROR                                                                          
    3/10                                                                           
    PLS-00994: Cursor Variables cannot be declared as part of a package            
    3/10                                                                           
    PL/SQL: Declaration ignored                                                    

  • Dynamic cursors in pro*c

    Please, what I need to do in order to be able
    to do something like this:
    EXEC SQL DECLARE :c CURSOR FOR :s;
    In other words: I want to use variables
    in cursor names.
    Is it possible ? How ?
    Thank you.

    Please, what I need to do in order to be able
    to do something like this:
    EXEC SQL DECLARE :c CURSOR FOR :s;
    In other words: I want to use variables
    in cursor names.
    Is it possible ? How ?
    Thank you.

  • JDBC 2.0 - Dynamic cursors

    Hi,
    I am trying to create a cursor, and i need to use some
    features of JDBC 2 like "scrolling backwards" and updating
    data from cursor relative position, but
    i got an exception, and e.printStack() infromed me
    this feature was not "yet" implemented.
    // ResultSet.afterLast() and ResultSet.previous()
    // raise an SQLException
    Is there any update that can "already" do it
    (FULL JDBC 2 implementation )?
    I would like to have it for 8.1.5/Solaris AND Lite/Win.
    Regards,
    Txr
    null

    Jose,
    Openlink Software provides full JDBC 2.0 compliancy - visit
    http://www.openlinksw.com for more information. Pay particular
    attention to the RowSetDemo applet if you download; Openlink's
    Rowset class will provide the functionality you require. All
    demos provide source code for your adapting purposes.
    Good luck!
    Jose Teixeira (guest) wrote:
    : Hi,
    : I am trying to create a cursor, and i need to use some
    : features of JDBC 2 like "scrolling backwards" and updating
    : data from cursor relative position, but
    : i got an exception, and e.printStack() infromed me
    : this feature was not "yet" implemented.
    : // ResultSet.afterLast() and ResultSet.previous()
    : // raise an SQLException
    : Is there any update that can "already" do it
    : (FULL JDBC 2 implementation )?
    : I would like to have it for 8.1.5/Solaris AND Lite/Win.
    : Regards,
    : Txr
    null

  • Huge query  with  parameter for to use Dynamic Cursor with Parameters

    Hi
    Is possible put the query below like dynmic cursor passing Parameters ?
    How can I do it ?
        OPEN P_CURSOR FOR
        WITH NOTIFICACAO AS(
          SELECT 
           t1.cd_consultora,
           t1.dc_nome_consultora,
           t2.nm_notificacao_cn,
           t2.dt_notificacao_cn dt_notificacao,
           t2.dt_atendimento_notificado,
           t1.cd_tipo_estrutura_comercial,
           t1.cd_estrutura_comercial
            FROM t_consultora t1, nc.t_nc_notificacao_cn t2
           WHERE t2.dt_notificacao_cn BETWEEN w_DTA_INI AND w_DTA_FIM
             AND t2.cd_consultora = t1.cd_consultora
             AND t1.cd_setor = w_cd_setor
             AND t1.cd_tipo_estrutura_comercial = p_tp_estrutura_comercial
             AND t1.cd_estrutura_comercial = p_cd_estrutura_comercial),
        T_NOTIFICADA AS ( select Count(t1.nm_notificacao_cn) over (partition by  t1.cd_consultora,t1.nm_notificacao_cn ) QTD_NOTAS,
                                 Count(t2.nm_item_notificacao_cn) over (partition by  t1.cd_consultora,t1.nm_notificacao_cn ) QTD_ITENS,
                                 T3.*
                                  from nc.t_nc_notificacao_cn t1,
                                       nc.t_nc_item_notificacao_cn  T2,
                                       NOTIFICACAO                  T3 
                                   where       t1.dt_notificacao_cn >= to_date('01/09/2006','dd/mm/yyyy')
                                    and   t3.nm_notificacao_cn = t1.nm_notificacao_cn
                                   and    t1.nm_notificacao_cn = t2.nm_notificacao_cn
                                   and    ((t2.cd_tipo_item_nc = 4 and t2.cd_subtipo_item_nc = 6)
                                           or t2.cd_tipo_item_nc = 2 or t2.cd_tipo_item_nc = 3)
                                           and t3.cd_consultora = t1.cd_consultora (+)  )  ,
        T_BLOQUEADA AS ( SELECT T4.* FROM
                     (SELECT  T3.*,
                            CASE WHEN T3.BLOQUEADA = -1 THEN  'Bloqueada'
                                 WHEN  T3.BLOQUEADA = 0 THEN
                              (CASE WHEN T3.QTD_NOTAS > 2 THEN
                                 CASE WHEN T3.QTD_ITENS > 8 THEN 'Atencao / Analise'
                                 ELSE
                                    'Normal'
                                 END
                               ELSE
                                 'Atencao / Analise'   
                              END)
                             END OBSERVACAO
                      FROM  (SELECT CASE WHEN NVL(T2.ID_CN_BLOQUEADA,1) = 1 then -1
                                   WHEN NVL(T2.ID_CN_BLOQUEADA,1) = 0  THEN 0
                                   END BLOQUEADA, T1.*
                        FROM   T_NOTIFICADA T1,
                               T_PS_CONSULTORA T2 
                               WHERE T1.CD_CONSULTORA = T2.CD_PESSOA)T3) T4 )
            select *
              from (SELECT t1.*, ROWNUM r_linha
               FROM (SELECT  cd_consultora,
                       dc_nome_consultora,
                       fnc_busca_telefone(CD_CONSULTORA, 1) TELEFONE1,
                       fnc_busca_telefone(CD_CONSULTORA, 2) TELEFONE2,
                        EMAIL,
                        observacao,
                       nm_notificacao_cn,
                       nvl(vl_total_final,0) vl_total_final,                  
                       dt_notificacao,
                       qt_produto_item_nc,
                      sg_notificacao,
                      ID_SITUACAO,
                       qtd_registros
                    FROM (SELECT /*+ INDEX(W5 I0_NC_TIPO_ITEM_NC) */
                       W1.cd_consultora,
                       W1.dc_nome_consultora,
                       fnc_busca_telefone(w1.CD_CONSULTORA, 1) TELEFONE1,
                       fnc_busca_telefone(w1.CD_CONSULTORA, 2) TELEFONE2,
                       fnc_busca_email(w1.CD_CONSULTORA) EMAIL,
                       W1.OBSERVACAO observacao,
                       W1.nm_notificacao_cn,
                       sum(W4.qt_produto_nf *
                           W4.vl_unitario_final_produto_nf) OVER(PARTITION BY W1.cd_consultora, W1.nm_notificacao_cn) vl_total_final,
                       W1.dt_notificacao,
                       sum(W4.qt_produto_nf) OVER(PARTITION BY W1.cd_consultora, W1.nm_notificacao_cn) qt_produto_item_nc,
                       'PENDENTE' sg_notificacao,
                       W5.dc_tipo_item_nc ID_SITUACAO,
                       W_qtd_registros qtd_registros
                        FROM T_BLOQUEADA               W1,
                             nc.t_nc_item_notificacao_cn W2,
                             nc.t_nc_produto_item_nc     W3,
                             nc.t_nc_produto_item_nf     W4,
                             nc.t_nc_tipo_item_nc        W5
                       WHERE W1.dt_atendimento_notificado is null
                         and W1.nm_notificacao_cn =
                             W2.nm_notificacao_cn
                         and W2.cd_tipo_item_nc = W5.cd_tipo_item_nc
                         and W2.nm_notificacao_cn =
                             W3.nm_notificacao_cn(+)
                         and W2.nm_item_notificacao_cn =
                             W3.nm_item_notificacao_cn(+)
                         and W3.nm_notificacao_cn =
                             W4.nm_notificacao_cn(+)
                         and W3.nm_item_notificacao_cn =
                             W4.nm_item_notificacao_cn(+)
                         and W3.nm_sequencia_produto_item_nc =
                             W4.nm_sequencia_produto_item_nc(+)
                         and W2.cd_tipo_item_nc not in (6, 7)
                         and ((W2.id_situacao_item_nc = 1) OR
                             (W2.id_situacao_item_nc = 3 OR
                             W2.id_solucao_definida is not null))
                      UNION
                      SELECT /*+ INDEX(W5 I0_NC_TIPO_ITEM_NC) */
                       W1.cd_consultora,
                       W1.dc_nome_consultora,
                       fnc_busca_telefone(w1.CD_CONSULTORA, 1) TELEFONE1,
                       fnc_busca_telefone(w1.CD_CONSULTORA, 2) TELEFONE2,
                       fnc_busca_email(w1.CD_CONSULTORA) EMAIL,
                       W1.OBSERVACAO observacao,
                       W1.nm_notificacao_cn,
                       sum(W4.qt_produto_nf *
                           W4.vl_unitario_final_produto_nf) OVER(PARTITION BY W1.cd_consultora, W1.nm_notificacao_cn) vl_total_final,
                       W1.dt_notificacao,
                       sum(W4.qt_produto_nf) OVER(PARTITION BY W1.cd_consultora, W1.nm_notificacao_cn) qt_produto_item_nc,
                       'ATENDIDO' sg_notificacao,
                       W5.dc_tipo_item_nc ID_SITUACAO,
                       W_qtd_registros qtd_registros
                        FROM T_BLOQUEADA                W1,
                             nc.t_nc_item_notificacao_cn W2,
                             nc.t_nc_produto_item_nc     W3,
                             nc.t_nc_produto_item_nf     W4,
                             nc.t_nc_tipo_item_nc        W5
                       WHERE W1.dt_atendimento_notificado is not null
                         and W1.nm_notificacao_cn =
                             W2.nm_notificacao_cn
                         and W2.cd_tipo_item_nc = W5.cd_tipo_item_nc
                         and W2.nm_notificacao_cn =
                             W3.nm_notificacao_cn(+)
                         and W2.nm_item_notificacao_cn =
                             W3.nm_item_notificacao_cn(+)
                         and W3.nm_notificacao_cn =
                             W4.nm_notificacao_cn(+)
                         and W3.nm_item_notificacao_cn =
                             W4.nm_item_notificacao_cn(+)
                         and W3.nm_sequencia_produto_item_nc =
                             W4.nm_sequencia_produto_item_nc(+)
                             )T2
    ---- here with NDS   I changed order by
                       ORDER BY DECODE(p_nm_asc_desc,0,DECODE(p_nm_col_ordem ,1, cd_consultora,2,dc_nome_consultora)) ASC, --,8,vl_total_final)) ASC,
                       DECODE(p_nm_asc_desc,1,DECODE(p_nm_col_ordem ,1, cd_consultora,2,dc_nome_consultora)) desc --,8,vl_total_final)) DESC
                             ) T1
               where rownum <= W_TO_REC)
             where r_linha >= W_FROM_REC;Is It Query very much great and how can I to pass parameters w_DTA_INI ,w_DTA_FIM, W_TO_REC,W_FROM_REc ....etc
    TIA

    I did (some time ago and it was a packaged procedure) something like
    Procedure p(p_one in datatype,p_two in datatype,p_dataset out sys_refcursor) is
      the_sql varchar2(32000);
      the_cursor sys_refcursor;
    begin
      the_sql = 'WITH NOTIFICACAO AS( ' ||
                '      SELECT ' ||
                '       t1.cd_consultora, ' ||
                '                               where       t1.dt_notificacao_cn >= to_date(''01/09/2006'',''dd/mm/yyyy'') ' ||  -- note the ''
                '           where rownum <= :W_TO_REC) ' ||   -- parameter 1
                '         where r_linha >= :W_FROM_REC ';     -- parameter 2
      open the_cursor for the_sql using p_one,p_two;  -- just by the book
    end p;if I remember correctly
    Regards
    Etbin

Maybe you are looking for