Dynamic query and Open Cursor fetch into ??

Hi;
I think we took the wrong turn some were... because looks like a dead end...
What I need to do:
Create a procedure to compare two generic tables in diferente databases and find rows that have diferent data.
(No restritions on what tables it might compare)
What I have done:
CREATE OR REPLACE PROCEDURE COMPARE_TABLES_CONTENT_V3(
tableName_A IN VARCHAR2, tableName_B IN VARCHAR2, filter IN VARCHAR2) AS
-- Get all collumns present in [TableName_A]
-- This is necessary to create a dynamic query
select column_name bulk collect
into v_cols1
from all_tab_columns
where table_name = v_tab1
and owner = nvl(v_own1, user)
order by column_id;
-- If there is no columns in table A ... them no need to proceed
if v_cols1.count = 0 then
dbms_output.put_line('[Error] reading table ' || tableName_A ||
' collumns information. Exit...');
return;
end if;
-- Collect Collumns information by ',' separated, for the query
for i in 1 .. v_cols1.count loop
compareCollumns := compareCollumns || ',' || v_cols1(i);
end loop;
-- Create the query that gives the diferences....
getDiffQuery := 'select ' || compareCollumns ||
' , count(src1) CNT1, count(src2) CNT2 from (select a.*, 1 src1, to_number(null) src2 FROM ' ||
tableName_A ||
' a union all select b.*, to_number(null) src1, 2 src2 from ' ||
tableName_B || ' b) group by ' || compareCollumns ||
' having count(src1) <> count(src2)';
Whats the problem?
I'm lost...I can access the query using debugging on the oracle procedure... and run it OK on a new SQL window. No problem here... its perfect.
But I dont know how to access this information inside the procedure, I need to format the information a bit...
I try a cursor...
open vCursor for getDiffQuery;
fetch vCursor into ??????? -- Into what... query, columns and tables is all dynamic...
close vCursor;
Any ideas..

Making the issue more simple....
At this point I have a oracle procedure that generates a dynamic sql query, based on the table names passed by parameter.
getDiffQuery := 'select ' || compareCollumns || (.....)
end procedure;
This ''getDiffQuery'' contains a query that gets the diferences in the tables. (Working fine)
I would like to access this information in the same procedure.
I cant use cursor because the table, columns... actualy all is dynamic based on the generated query:( !

Similar Messages

  • Link Query and Ref Cursor Query

    Hi all!!
    How can I link Query and Ref Cursor Query??
    I mean, How can I pass input parameters to the PL/SQL procedure if they are not User parameters but they come from another table??
    Thanks a lot
    F.

    I have searched the forum and this is the closest to my problem.
    Just started using ref cursors in my reports.
    The problem I am running into is that I have two ref cursor queries in my report - they each contain a column named seq_no which forms a join (in the database) .
    My report returns the correct number of records in each query, but I can't find a way to enforce the join. I've tried all the methods I can think of including combining the results into one query.
    The IDE won't let me join on a column and when I join on the group (which I make only contain the seq_no fields) that join is ignored.
    Can anyone help me on this?

  • VBPA and VBAK query using OPEN CURSOR... anyway to skip buffer?

    Hi all,
    I have a query which VBPA inner join VBAK. In this query, I am using VBPA-KUNNR and VBPA-PARVW to query out data. I know VBPA holds a lot of data and querying in this way will be very heavy.
    So I use OPEN CURSOR to query the SELECT .. INNER JOIN for these two tables...
    It's fast for partners with few sales document.
    But, i noticed the query will do a buffer before it process the query...
    So my question is, is there a way to by-pass the buffer so it can immediately query?
    Thanks,
    William Wilstroth

    Hi Sandeep,
    I did put the BYPASSIUNG BUFFER syntax in the query. The result is still the same...
    I wonder if it's just querying by VBPA-KUNNR and VBPA-PARVW is causing it? On the other hand, I think it's not because I am using VBPA-PARVW key field...
    Hmmm... I wonder why in the first time query, it will go to buffer and it takes out some time...
    Thanks,
    William Wilstroth

  • Dynamic query and parameters

    Hi there,
    I have created a procedure and passing values via parameters but then the sql statement takes it as a string rather than parameters. Could you please let me know what it is that I am doing wrong.
    Code is as follows:
    CREATE OR REPLACE FUNCTION GetTableData(p_vInTname IN VARCHAR2
      ,p_dInLastPubTms IN DATE
    RETURN CLOB
    IS
      vStrSqlQuery VARCHAR2(32767);
      TYPE ref_cursor IS REF CURSOR;
      rc_tablevalues ref_cursor;
      lc_XML CLOB;
    BEGIN
      vStrSqlQuery:= q'[SELECT dbms_xmlgen.getxml('SELECT * FROM p_vInTname ' ||' WHERE record_update_tms >= TO_DATE(p_dInLastPubTMS,'MM/DD/YYYY HH24:MI:SS')) FROM dual]';
      DBMS_OUTPUT.put_line(vStrSqlQuery);
      OPEN rc_tablevalues FOR vStrSqlQuery;
      FETCH rc_tablevalues INTO lc_XML;
      CLOSE rc_tablevalues;
      RETURN lc_XML;
      printClob(lc_XML);
    END GetTableData;
    This compiled successfully.
    Another procedure for printing
    Create or replace PROCEDURE printClob (result IN OUT NOCOPY CLOB) IS
        xmlstr   VARCHAR2 (32767);
        line     VARCHAR2 (2000);
      BEGIN
        xmlstr := DBMS_LOB.SUBSTR (result, 32767);
        LOOP
           EXIT WHEN xmlstr IS NULL;
           line := SUBSTR (xmlstr, 1, INSTR (xmlstr, CHR (10)) - 1);
           DBMS_OUTPUT.put_line ('| ' || line);
           xmlstr := SUBSTR (xmlstr, INSTR (xmlstr, CHR (10)) + 1);
        END LOOP;
      END printClob;
    I am trying to test it to see how it behaves, so created a test procedure which is:
    CREATE OR REPLACE PROCEDURE SANDEEP_TEST_LAMXML
    IS
    lv_x CLOB;
    BEGIN
      lv_x := CTN_PUB_CNTL_EXTRACT_PUBLISH.GetTableData('TRKFCG_SBDVSN',TO_DATE('04/27/2015 19:57:10', 'MM/DD/YYYY HH24:MI:SS'));
    END;
    The above one too compiles successfully. However when I set a break point and then try to pass through the function instead of seeing the parameter in the second part of the query, I am seeing it as:
    SELECT dbms_xmlgen.getxml('SELECT * FROM p_vInTname ' ||' WHERE record_update_tms >= TO_DATE(p_dInLastPubTMS,'MM/DD/YYYY HH24:MI:SS')) FROM dual
    What is that I am doing wrong that I am unable to see the runtime parameters being passed into the variables of the query? Can any one suggest something? I am handling dynamic queries and also a solution such as the above for the first time.
    Thanks in advance.

    There are quite a few errors and here's a working version:
    CREATE OR REPLACE FUNCTION GetTableData(p_vInTname IN VARCHAR2
      ,p_dInLastPubTms IN VARCHAR2
    RETURN CLOB
    IS
      vStrSqlQuery VARCHAR2(32767);
      TYPE ref_cursor IS REF CURSOR;
      rc_tablevalues ref_cursor;
      lc_XML CLOB;
    BEGIN 
      vStrSqlQuery:= q'[SELECT dbms_xmlgen.getxml('SELECT * FROM ]'||p_vInTname||q'[ WHERE record_update_tms >= TO_DATE('']'||p_dInLastPubTMS||q'['',''MM/DD/YYYY HH24:MI:SS'')') FROM dual]';
      DBMS_OUTPUT.put_line(vStrSqlQuery);
      OPEN rc_tablevalues FOR vStrSqlQuery;
      FETCH rc_tablevalues INTO lc_XML;
      CLOSE rc_tablevalues;
      printClob(lc_XML);
      RETURN lc_XML;
    END GetTableData;
    CREATE OR REPLACE PROCEDURE SANDEEP_TEST_LAMXML
    IS
    lv_x CLOB;
    BEGIN
      lv_x := GetTableData('TRKFCG_SBDVSN','04/27/2015 19:57:10');
    END;
    This version will be easier to understand:
    CREATE OR REPLACE FUNCTION GetTableData(p_vInTname IN VARCHAR2 
      ,p_dInLastPubTms IN VARCHAR2 
    RETURN CLOB 
    IS 
      vStrSqlQuery VARCHAR2(32767); 
      TYPE ref_cursor IS REF CURSOR; 
      rc_tablevalues ref_cursor; 
      lc_XML CLOB; 
    BEGIN  
      vStrSqlQuery:= 'SELECT * FROM '||p_vInTname||' WHERE record_update_tms >= TO_DATE('''||p_dInLastPubTMS||''',''MM/DD/YYYY HH24:MI:SS'')';
      DBMS_OUTPUT.put_line(vStrSqlQuery); 
    SELECT dbms_xmlgen.getxml(vStrSqlQuery)
      INTO lc_XML
      FROM dual;
      printClob(lc_XML); 
      RETURN lc_XML; 
    END GetTableData; 

  • Dynamic sql and updating cursors

    hi to anyone,
    we use few temporary global tables which will be created on the fly if not present ( the reason is - they are not created by power designer ).
    addressing theses tables is only possible by using dynamic sql via "execute immediate" because they may not be known to the compiler as they are not created yet.
    Now I defined a cursor to walk through the table - using cursor reference "ref cursor". Using this cursor works, but i found no way using this cursor for update. i.e. declaring as .. for update of and later putting it into an execute immediate like " execute immediate 'update ' || w_temp_table || ' set f1 = :1, f2 = :2 where current of ' || w_cursor using w_1, w_2;" It doesnt work if I block this command using "begin / end".
    Does naybody know a solution ?
    thanks in advance
    wilko

    Thanks todd,
    my main purpose has been just using the dynamic cursor for update as I know that this is quite easy and also fast. I didnt concern about locking all rows I walk through. But you are right - at end you will use the most easy way. So what I did because of another cursor problem ( with analytical functions ) - I defined the temporary table before compiling and everything is much more convenient.
    thanks for help
    wilko

  • Dynamic Query and Collect Statement.

    Hi Gurus....
    Please explain me how to write dynamic Query,,, Pl. give me with example.
    Also would like to know basics of Collect statement and it's use..
    Thanks
    Ritesh

    Hi Ritesh,
    COLLECT is used to create unique or compressed datsets. The key fields are the default key fields of the internal table itab . If all non-numeric fields are same in the internal table then it will add numeric fields and maintains a single entry
    If you use only COLLECT to fill an internal table, COLLECT makes sure that the internal table does not contain two entries with the same default key fields.
    Check this link to know about COLLECT statement
    http://www.sts.tu-harburg.de/teaching/sap_r3/ABAP4/collect.htm
    Dynamic query can be built in SAP with the help of () values.
    DATA:
    V_TABNAME TYPE DDO2L-TABNAME,
    V_CONDTION TYPE STRING.
    V_TABNAME = 'MARA'.
    V_CONDTION = 'MATNR LIKE 'S*'.
    SELECT MATNR
      FROM <b>(V_TABNAME)</b>
      INTO TABLE ITAB
    WHERE <b>(V_CONDTION)</b>.
    Thanks,
    Vinay

  • PreparedStatement and open cursors

    Hi,
    i write an application where it is necessary to get a lot of preparedStatements in one connection. The preparedStatements are used
    only once and they are closed after the usage. But it seems to me that this close
    has no effect. Depending on the value in open cursors the error ORA - 01000 raises and it is not possible to get another preparedStatement without closing and opening the connection. But that increases the runtime to much and the application is a performance-critical application.
    Does anyone have an idea how to solve the problem?
    Thanks

    >
    Any thoughts what could be the problem. Only time I ever got them was because the result set, statement, connection wasn't being closed or wasn't being closed in the correct order.

  • Dynamic Query and default run-time values

    I am trying to build a dynamic query within dreamweaver and
    retain access from the bindings panel.
    here is a simple pseudo-query I want to expand on.
    "SELECT object FROM objects_table WHERE widget_number =
    widgets"
    widgets is set up as a variable with a run-time value that
    relates to $_GET['widgets']
    this works fine but now i want to expand on this so the query
    returns all results if $_GET['widgets'] is undefined. I was hoping
    I could set the default value for widgets to equal widget_number so
    I would get....
    "SELECT object FROM objects_table WHERE widget_number =
    widget_number" but the runtime query is actually
    "SELECT object FROM objects_table WHERE widget_number =
    'widget_number' " which obviously doesn't work.
    I can alter the query manually from the code view but then I
    lose access to the bindings panel as dreamweaver doesn't parse the
    query properly.
    Any pointers?
    Thanks in advance
    - Andrew

    Andy Millne wrote:
    > That will work fine server-side yeah but dreamweaver
    cannot parse the code at
    > design time so by altering the code in this way you lose
    access to the bindings
    > panel and all the server behaviours that depend on the
    recordset have
    > exclamation marks alongside.
    This is simply a question of organizing your workflow. As you
    have
    discovered, Dreamweaver no longer recognizes a recordset if
    you make
    changes to the basic structure of the code. The answer is to
    use
    Dreamweaver to construct your page using an unaltered
    recordset. Once
    the design stage is complete, make the changes required by
    inserting
    your conditional statement. Yes, the fieldnames disappear
    from the
    Bindings panel, and you get exclamation marks in the Server
    Behaviors
    panel, but that's not important. If you need to restore them
    for any
    reason, just wrap the changes in /* */ comments. Remove the
    comments
    when you have finished.
    David Powers, Adobe Community Expert
    Author, "The Essential Guide to Dreamweaver CS3" (friends of
    ED)
    Author, "PHP Solutions" (friends of ED)
    http://foundationphp.com/

  • Cursor fetch into

    I have a function, to which i pass a sql statement.In the function using the cursor i get the output of the sql statemnt into a output variable. This function works fine, but for one particular select statement it takes[u] over an hour to execute in the FETCH...INTO statement specifically. The same select statement when executed outside in sql editor returns in under 2 mins.
    The output of the sql is 5 records. Any ideas on why it is taking forever in the FETCH...INTO statment?
    FUNCTION getOutput(p_sql VARCHAR2)
    RETURN VARCHAR2
    AS
    TYPE extractlinecurtype IS REF CURSOR;
    cur_extract extractlinecurtype;
    v_oneextractline VARCHAR2 (32767);
    v_output VARCHAR2 (32767) := NULL;
    crlf CHAR (2) := CHR (10) || CHR (13);
    BEGIN
    OPEN cur_extract FOR p_sql;
    dbms_output.put_line(sysdate);
    LOOP
    FETCH cur_extract
    INTO v_oneextractline;
    EXIT WHEN cur_extract%NOTFOUND;
    v_output := v_output || CHR (10) || v_oneextractline;
    END LOOP;
    IF cur_extract%ISOPEN
    THEN
    CLOSE cur_extract;
    END IF;
    v_output := v_output || crlf || crlf;
    return v_output;
    EXCEPTION
    WHEN OTHERS
    THEN
    dbms_output.put_line('error in getoutput' || SQLCODE || SQLERRM);
    RETURN NULL;
    END getOutput;

    I cannot send the sql cause it uses our internal tables. My question is why does a query take under 2mins to run in sql editor and over an hr in pl/sql with cursor?
    Is there something wrong in declaration?

  • Dynamic sql and ref cursors URGENT!!

    Hi,
    I'm using a long to build a dynamic sql statement. This is limited by about 32k. This is too short for my statement.
    The query results in a ref cursor.
    Does anyone have an idea to create larger statement or to couple ref cursors, so I can execute the statement a couple of times and as an result I still have one ref cursor.
    Example:
    /* Determine if project is main project, then select all subprojects */
    for i in isMainProject loop
    if i.belongstoprojectno is null then
    for i in ProjectSubNumbers loop
    if ProjectSubNumbers%rowcount=1 then
    SqlStatement := InitialStatement || i.projectno;
    else
    SqlStatement := SqlStatement || PartialStatement || i.projectno;
    end if;
    end loop;
    else
    for i in ProjectNumber loop
    if ProjectNumber%rowcount=1 then
    SqlStatement := InitialStatement || i.projectno;
    else
    SqlStatement := SqlStatement || PartialStatement || i.projectno;
    end if;
    end loop;
    end if;
    end loop;
    /* Open ref cursor */
    open sql_output for SqlStatement;
    Thanks in advance,
    Jeroen Muis
    KCI Datasystems BV
    mailto:[email protected]

    Example for 'dynamic' ref cursor - dynamic WHERE
    (note that Reports need 'static' ref cursor type
    for building Report Layout):
    1. Stored package
    CREATE OR REPLACE PACKAGE report_dynamic IS
    TYPE type_ref_cur_sta IS REF CURSOR RETURN dept%ROWTYPE; -- for Report Layout only
    TYPE type_ref_cur_dyn IS REF CURSOR;
    FUNCTION func_dyn (p_where VARCHAR2) RETURN type_ref_cur_dyn;
    END;
    CREATE OR REPLACE PACKAGE BODY report_dynamic IS
    FUNCTION func_dyn (p_where VARCHAR2) RETURN type_ref_cur_dyn IS
    ref_cur_dyn type_ref_cur_dyn;
    BEGIN
    OPEN ref_cur_dyn FOR
    'SELECT * FROM dept WHERE ' | | NVL (p_where, '1 = 1');
    RETURN ref_cur_dyn;
    END;
    END;
    2. Query PL/SQL in Reports
    function QR_1RefCurQuery return report_dynamic.type_ref_cur_sta is
    begin
    return report_dynamic.func_dyn (:p_where);
    end;
    Regards
    Zlatko Sirotic
    null

  • How ca n i build a dynamic query in a cursor

    i have a cursor in a procedure. it runs some sql query. i want to build a part of this query dynamically based on the parameters passed to this procedure.how should i do thatnow the cursor is before the begin end structure and if i have to build a query whose return results are to be processed then i have to write that in a cursor and i cannot write a cursor inside a begin end(that's my understanding) and only way to build a query is to build it in a begin end . i think reference cursors can be used to accomplish this task. can someone guide me with this.thnx in advance.

    This is straightforward programming logic....
    CREATE OR REPLACE FUNCTION my_qry
       (p1 IN VARCHAR2 := NULL, p2 IN VARCHAR2 := NULL)
       RETURN sys_refcursor
    IS
       stmt VARCHAR2(32767) :='select creation_date from mytable';
       clause1 VARCHAR2(32767) := 'app_id=';
       clause2 VARCHAR2(32767) := 'ticket_number=';
       rc sys_refcursor;
    BEGIN
       CASE
          WHEN p1 IS NOT NULL AND p2 IS NOT NULL
          THEN
             open rc for stmt||
                 ' WHERE '||clause1||':1 AND '||
                 clause2||':2' USING p1, p2;
          WHEN p1 IS NOT NULL AND p2 IS NULL
          THEN
             open rc for stmt||
                 ' WHERE '||clause1||':1 ' USING p1;
          WHEN p1 IS NULL AND p2 IS NOT NULL
          THEN
             open rc for stmt||
                 ' WHERE '||clause2||':1 ' USING p2;
          ELSE
             open rc for stmt;
        END CASE;
        RETURN rc;
    END;
    [pre]
    Cheers, APC                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Can we change/Modify BI server generated Sql query and run to fetch data

    Hi,
    My client is saying that there is an option to modify bi server generated sql query to fetch data from source.
    question:As a request is made in presentation services, A dynamic sql query is generated and fetches data from source. all this is loggedin Nqlquery log..well can we change/modify the sql query generated and run modified sql query to fetch data from source. ., if so how? if not why?
    Thanks in advance
    Edited by: user10794468 on Jun 16, 2009 6:29 PM
    Edited by: user10794468 on Aug 12, 2009 6:58 PM

    Thank you so much for your reply..
    ..Can we also modify sql query generated by bi server to fetech data. the query's which we see in query log file..

  • Cursor Fetch into Record vs Record Components

    Anyone,
    What are pros and cons of the use of the cursor method that fatches into a single record value vs. that of record components?
    I am just not seeing why you might use one vs other so was curious if their is something I am missing in reagrds to performance or temp space required or anything like that????
    Thanks for any help,
    Miller

    You should use record components when possible. It is easier to code and read.
    Cursor loops are great:
    for c_rec in select a, b, c from t1, t2 where t1.a = t2.a loop
    dbms_output.put_line(c_rec.b || c_rec.a);
    end loop;
    In the above case you don't even have to declare c_rec!
    Tom Best

  • Dynamic query with ref cursors

    please help me out there.
    can you give an example of how to construct a procedure using ref cursors.
    say if I had an employee table.
    employee table
    first name
    last name
    position
    dept
    I would have three input parameters, last name, position, dept. Sometimes only one parameters would be passed. Sometimes only two or sometimes all three.
    How can I construct the procedure being that the parameters will be dynamic
    thanks.

    Don't worry user484105 I don't do kicking, sarcasm and bad humour are other matters though.
    Yes you can use sys_refcursor, in fact all the tests that Todd and I have supplied, have done just that. Do you have a development database to work in?
    if so I would recommend
    1. Run demobld.sql if you don't already have emp table.
    2. Copy my second post in your other thread.
    3. Edit out all the sqlplus output and the first four columns.
    4. If any of this puzzles you see if you can find the answer in the SQL Reference, PL/SQL Guide or SQL*Plus manuals
    http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14200/toc.htm
    http://download-east.oracle.com/docs/cd/B19306_01/appdev.102/b14261/toc.htm
    http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14357/toc.htm
    5. If you can't find the answer post what you have and the error here.
    6. It is probably best if you use sqlplus for this.
    You will learn a lot if you can do this.

  • Help with dynamic text and hand cursor

    The buttons that I am creating are not displaying the hand
    cursor. I tried searching for an answer, and have found nothing.
    They are movieclip buttons with a dynamic text field. I already
    switched them out to non-selectable text, and I am using:
    b1.buttonMode = true;

    Perfect. I knew it was some little snippet that I was
    forgetting. I made a temporary fix of creating a 0% alpha box over
    the button like a fake click area above the text, and that worked
    but I know that it was a half-arsed way of working around it.
    Thanks.

Maybe you are looking for

  • Displaying an alert (Applescript or otherwise) from shell script?

    I have a point in a shell script where I'd like to put up an alert dialogue on a particular error condition. The script runs in the background and doesn't have a terminal window. I tried writing a little applescript that uses the applescript alert co

  • HT3939 how to know my mobile model 3gs or 4s etc.??

    i have bought an iphone mobile and i can't know to which model belong it 3gs or 4s or what?!! vesion is : 6.0.1(9A405) . PLEAZE HELP! <Personal Information Edited by Host>

  • Bug on uninstall/install?

    Hello, I am wondering if the issue I entered on this posting could be considered a bug: .jws default program is notepad, not jdeveloper Here is my situation: I am on windows 7, have two editions of jdeveloper, 11.1.1.6.0 (not explicitly relevant) and

  • IWEb hit counter look alike

    I just recently migrated from idisk to a FTP server and am looking for a new hit counter. I've grown accustomed to the look of the hit counter that iWeb provided. Can anyone lead me to a similar looking hit counter that iWeb uses?

  • Outlook 2013 Email Header Being Cut Off

    Outlook 2013 is cutting off the email header on multiple emails.  See screenshot below.