Pivot and dynamic SQL

Hi Team,
I need to write a SQL to cater the requirements. Below is my requirements:
pagename fieldname fieldvalue account_number consumerID
AFAccountUpdate ArrangementsBroken dfsdff 1234 1234
AFAccountUpdate ArrangementsBroken1 dfsdff 1234 1234
AFAccountUpdate ArrangementsBroken2 dfsdff 1234 1234
AFAccountUpdate ArrangementsBroken2 dfsdff 12345 12345
AFAccountUpdate ArrangementsBroken1 addf 12345 12345
Create table test_pivot_dynamic
pagename varchar(200),
fieldname Varchar(200),
fieldvalue varchar(500),
N9_Router_Account_Number bigint,
TC_Debt_Item_Reference bigint
--Input
insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken','addf',1234,1234)
insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken1','dfsdff',1234,1234)
insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken2','fder',1234,1234)
insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken2','dfdfs',12345,12345)
insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken1','dfdwe',12345,12345)
insert into test_pivot_dynamic Values('AFAccountUpdate1','Arrangements','addf',1234,1234)
insert into test_pivot_dynamic Values('AFAccountUpdate1','Test1','dfsdff',1234,1234)
--Expected output:
Select 1234,1234,'AFAccountUpdate','ArrangementsBroken','addf','ArrangementsBroken1','dfsdff','ArrangementsBroken2','fder','ArrangementsBroken2','fder'
Select 12345,12345,'AFAccountUpdate','ArrangementsBroken','addf','ArrangementsBroken1','dfdwe','ArrangementsBroken2','dfdfs'
Select 1234,1234,'AFAccountUpdate1','Arrangements','addf','Test1','dfsdff'
so basically we have to pivot and dynamic sql and insert the expected output to a common table which will have all the required fields
Thanks,Ram.
Please don't forget to Marked as Answer if my post solved your problem and use Vote As Helpful if a post was useful. It will helpful to other users.

This should give you what you're looking for
SELECT N9_Router_Account_Number,TC_Debt_Item_Reference,PageName,
MAX(CASE WHEN SEQ = 1 THEN fieldname END) AS fieldname1,
MAX(CASE WHEN SEQ = 1 THEN fieldvalue END) AS fieldvalue1,
MAX(CASE WHEN SEQ = 2 THEN fieldname END) AS fieldname2,
MAX(CASE WHEN SEQ = 2 THEN fieldvalue END) AS fieldvalue2,
MAX(CASE WHEN SEQ = 3 THEN fieldname END) AS fieldname3,
MAX(CASE WHEN SEQ = 3 THEN fieldvalue END) AS fieldvalue3,
MAX(CASE WHEN SEQ = 4 THEN fieldname END) AS fieldname4,
MAX(CASE WHEN SEQ = 4 THEN fieldvalue END) AS fieldvalue4
FROM
SELECT *,ROW_NUMBER() OVER (PARTITION BY N9_Router_Account_Number,TC_Debt_Item_Reference,PageName ORDER BY PageName) AS SEQ,*
FROM test_pivot_dynamic
)t
GROUP BY N9_Router_Account_Number,TC_Debt_Item_Reference,PageName
To make it dynamic see
 http://www.beyondrelational.com/modules/2/blogs/70/posts/10791/dynamic-crosstab-with-multiple-pivot-columns.aspx
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

Similar Messages

  • Difference between Static SQL Query and Dynamic SQL Query.

    Hi,
    Please explain the basic difference between static and dynamic sql queries. Please explain with example.

    Static: http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10472/static.htm
    Dynamic: http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10472/dynamic.htm

  • ORA-01008 with ref cursor and dynamic sql

    When I run the follwing procedure:
    variable x refcursor
    set autoprint on
    begin
      Crosstab.pivot(p_max_cols => 4,
       p_query => 'select job, count(*) cnt, deptno, row_number() over (partition by job order by deptno) rn from scott.emp group by job, deptno',
       p_anchor => Crosstab.array('JOB'),
       p_pivot  => Crosstab.array('DEPTNO', 'CNT'),
       p_cursor => :x );
    end;I get the following error:
    ^----------------
    Statement Ignored
    set autoprint on
    begin
    adsmgr.Crosstab.pivot(p_max_cols => 4,
    p_query => 'select job, count(*) cnt, deptno, row_number() over (partition by
    p_anchor => adsmgr.Crosstab.array('JOB'),
    p_pivot => adsmgr.Crosstab.array('DEPTNO', 'CNT'),
    p_cursor => :x );
    end;
    ORA-01008: not all variables bound
    I am running this on a stored procedure as follows:
    create or replace package Crosstab
    as
        type refcursor is ref cursor;
        type array is table of varchar2(30);
        procedure pivot( p_max_cols       in number   default null,
                         p_max_cols_query in varchar2 default null,
                         p_query          in varchar2,
                         p_anchor         in array,
                         p_pivot          in array,
                         p_cursor in out refcursor );
    end;
    create or replace package body Crosstab
    as
    procedure pivot( p_max_cols          in number   default null,
                     p_max_cols_query in varchar2 default null,
                     p_query          in varchar2,
                     p_anchor         in array,
                     p_pivot          in array,
                     p_cursor in out refcursor )
    as
        l_max_cols number;
        l_query    long;
        l_cnames   array;
    begin
        -- figure out the number of columns we must support
        -- we either KNOW this or we have a query that can tell us
        if ( p_max_cols is not null )
        then
            l_max_cols := p_max_cols;
        elsif ( p_max_cols_query is not null )
        then
            execute immediate p_max_cols_query into l_max_cols;
        else
            RAISE_APPLICATION_ERROR(-20001, 'Cannot figure out max cols');
        end if;
        -- Now, construct the query that can answer the question for us...
        -- start with the C1, C2, ... CX columns:
        l_query := 'select ';
        for i in 1 .. p_anchor.count
        loop
            l_query := l_query || p_anchor(i) || ',';
        end loop;
        -- Now add in the C{x+1}... CN columns to be pivoted:
        -- the format is "max(decode(rn,1,C{X+1},null)) cx+1_1"
        for i in 1 .. l_max_cols
        loop
            for j in 1 .. p_pivot.count
            loop
                l_query := l_query ||
                    'max(decode(rn,'||i||','||
                               p_pivot(j)||',null)) ' ||
                                p_pivot(j) || '_' || i || ',';
            end loop;
        end loop;
        -- Now just add in the original query
        l_query := rtrim(l_query,',')||' from ( '||p_query||') group by ';
        -- and then the group by columns...
        for i in 1 .. p_anchor.count
        loop
            l_query := l_query || p_anchor(i) || ',';
        end loop;
        l_query := rtrim(l_query,',');
        -- and return it
        execute immediate 'alter session set cursor_sharing=force';
        open p_cursor for l_query;
        execute immediate 'alter session set cursor_sharing=exact';
    end;
    end;
    /I can see from the error message that it is ignoring the x declaration, I assume it is because it does not recognise the type refcursor from the procedure.
    How do I get it to recognise this?
    Thank you in advance

    Thank you for your help
    This is the version of Oracle I am running, so this may have something to do with that.
    Oracle9i Enterprise Edition Release 9.2.0.8.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.8.0 - Production
    I found this on Ask Tom (http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:3027089372477)
    Hello, Tom.
    I have one bind variable in a dynamic SQL expression.
    When I open cursor for this sql, it gets me to ora-01008.
    Please consider:
    Connected to:
    Oracle8i Enterprise Edition Release 8.1.7.4.1 - Production
    JServer Release 8.1.7.4.1 - Production
    SQL> declare
      2    type cur is ref cursor;
      3    res cur;
      4  begin
      5    open res for
      6    'select * from (select * from dual where :p = 1) connect by 1 = 1'
      7    using 1;
      8  end;
      9  /
    declare
    ERROR at line 1:
    ORA-01008: not all variables bound
    ORA-06512: at line 5
    SQL> declare
      2    type cur is ref cursor;
      3    res cur;
      4  begin
      5    open res for
      6    'select * from (select * from dual where :p = 1) connect by 1 = 1'
      7    using 1, 2;
      8  end;
      9  /
    PL/SQL procedure successfully completed.
    And if I run the same thing on 10g -- all goes conversely. The first part runs ok, and the second
    part reports "ORA-01006: bind variable does not exist" (as it should be, I think). Remember, there
    is ONE bind variable in sql, not two. Is it a bug in 8i?
    What should we do to avoid this error running the same plsql program code on different Oracle
    versions?
    P.S. Thank you for your invaluable work on this site.
    Followup   June 9, 2005 - 6pm US/Eastern:
    what is the purpose of this query really?
    but it would appear to be a bug in 8i (since it should need but one).  You will have to work that
    via support. I changed the type to tarray to see if the reserved word was causing a problem.
    variable v_refcursor refcursor;
    set autoprint on;
    begin 
         crosstab.pivot (p_max_cols => 4,
                 p_query => 
                   'SELECT job, COUNT (*) cnt, deptno, ' || 
                   '       ROW_NUMBER () OVER ( ' || 
                   '          PARTITION BY job ' || 
                   '          ORDER BY deptno) rn ' || 
                   'FROM   emp ' ||
                   'GROUP BY job, deptno',
                   p_anchor => crosstab.tarray ('JOB'),
                   p_pivot => crosstab.tarray ('DEPTNO', 'CNT'),
                   p_cursor => :v_refcursor);
    end;
    /Was going to use this package as a stored procedure in forms but I not sure it's going to work now.

  • NULL and dynamic SQL

    If table testrh2 has the following columns and data
    col1 --> NULL
    col2 --> 2
    and table testrh has the following columsn and data
    col1 --> NULL
    How could I write a dynamic SQL statement to join on the nulls? I've written the following block as a starting point.
    declare
    cursor c1 is select col1 from isis.testrh;
    lval varchar2(1000);
    lval2 varchar2(1000);
    begin
    for r1 in c1 loop
    lval := 'select col2 from isis.testrh2 where col1 = '||r1.col1;
    execute immediate lval into lval2;
    dbms_output.put_line(lval2);
    end loop;
    end;

    You can't compare null values with '=' in Oracle SQL.
    Null can only be compared with <column> is null .
    You can see it when you try these two queries:
    select * from dual where null is null;  -- you will see one row
    select * from dual where null=null;  -- you will see no rowsThat's why you have to write something like
    (<column1>=<column1>   or   (<column1> is null and <column2> is null))This should also work with null:
    decode(<column1>,<column2>,1,0)=1By the way, why do you use dynamic sql?
    lval := 'select col2 from isis.testrh2 where col1 = '||r1.col1;
    I think you could replace your two lines ( lval:= ... AND execute immediate) by this:
    begin
      select col2
      into lval
      from isis.testrh2
      where decode(col1,r1.col1,1,0)=1;
      dbms_output.put_line('lval='||lval);
    exception
    when no_data_found then
      dbms_output.put_line('no data found'); -- or whatever you want
    end;Edited by: hartmutm on 02.10.2010 23:54

  • Strange behavior when searching a phrase using reg exp and dynamic sql

    Hi,
    I have a strange issue while using dynamic sql for an apex page. I have a requirement to search a string in the database column which is entered by user on a page item. The search process should search the whole phrase only.
    I have a query generated dynamically in the back end and use it in a cursor in the stored procedure
      SELECT t.group_cn , t.group_desc, t.group_type, t.partner_organization_id, t.partner_organization
      FROM vr_idm_group t WHERE regexp_like(t.group_desc,'(^|\W)HR Selection & Assignment(\W|$)', 'i')The pl sql code with the dynamic sql statements are below.
       IF p_search_process NOT in ('PARTNER') THEN
          OPEN v_cursor FOR v_sql;
       ELSE
          OPEN v_cursor FOR v_sql USING p_search_id;
       END IF;
       LOOP
          FETCH v_cursor INTo v_obj.group_cn, v_obj.group_desc, v_obj.group_type, v_obj.partner_organization_id,
             v_obj.partner_organization, v_obj.match_count;
          EXIT WHEN v_cursor%NOTFOUND ;
          v_search_array.extend;
          v_search_array(v_search_array.last) := v_obj;
          dbms_output.put_line(v_sql);
       END LOOP;The search works fine if the search string does not contain any special character like &,- etc.
    However, if the search string contains any special character, it does not return any thing. This strange issue happens only if I call the procedure from the apex page and the search string contains a special character. (please note that the procedure works fine even from apex if the string does not have a special character). When I debugged this, found that, the cursor does not fetch any rows (it is supposed to fetch two rows) for unknown reason. When I run the query separately, it returns the two rows (in which the column group_desc contains the search string "HR Selection & Assignment") as desired. Also, when I test the procedure in the back end (PLSQL developer), it works fine.
    Any idea, what is causing this strange behaviour?
    Advance thanks.
    Regards,
    Natarajan

    i don't see anything about a dataProvider.  you're assigning a source for a scrollpane.  scrollpane's don't have a dataProvider property.
    anyway, other than arrayRun always being false when that last if-statement executes, what's the problem?  doesn't that movieclip display when that 2nd branch of the last if-statement executes (assuming instance is defined correctly etc)?

  • Insert into using a select and dynamic sql

    Hi,
    I've got hopefully easy question. I have a procedure that updates 3 tables with 3 different update statements. The procedure goes through and updates through ranges I pass in. I am hoping to create another table which will pass in those updates as an insert statement and append the data on to the existing data.
    I am thinking of using dynamic sql, but I am sure there is an easy way to do it using PL/SQL as well. I have pasted the procedure below, and what I'm thinking would be a good way to do it. Below I have pasted my procedure and the bottom is the insert statement I want to use. I am faily sure I can do it using dynamic SQL, but I am not familiar with the syntax.
    CREATE OR REPLACE PROCEDURE ACTIVATE_PHONE_CARDS (min_login in VARCHAR2, max_login in VARCHAR2, vperc in VARCHAR2) IS
    BEGIN
    UPDATE service_t SET status = 10100
    WHERE poid_id0 in
    (SELECT poid_id0 FROM service_t
    WHERE poid_type='/service/telephony'
    AND login >= min_login AND login <= max_login);
    DBMS_OUTPUT.put_line( 'Service Status:' || sql%rowcount);
    UPDATE account_t SET status = 10100
    WHERE poid_id0 IN
    (SELECT account_obj_id0 FROM service_t
    WHERE poid_type = '/service/telephony'
    AND login >= min_login AND login <= max_login);
    DBMS_OUTPUT.put_line( 'Account Status:' || sql%rowcount);
    UPDATE account_nameinfo_t SET title=Initcap(vperc)
    WHERE obj_id0 IN
    (SELECT account_obj_id0 FROM service_t
    WHERE poid_type='/service/telephony'
    AND login >=min_login AND login <= max_login);
    DBMS_OUTPUT.put_line('Job Title:' || sql%rowcount);
    INSERT INTO phone_card_activation values which = 'select a.status, s.status, s.login, to_char(d.sysdate,DD-MON-YYYY), ani.title
    from account_t a, service_t s, account_nameinfo_t ani, dual d
    where service_t.login between service_t.min_login and service_t.max_login
    and ani.for_key=a.pri_key
    and s.for_key=a.pri_key;'
    END;
    Thanks for any advice, and have a good weekend.
    Geordie

    Correct my if I am wrong but aren't these equal?
    UPDATE service_t SET status = 10100
    WHERE poid_id0 in
    (SELECT poid_id0 FROM service_t
    WHERE poid_type='/service/telephony'
    AND login >= min_login AND login <= max_login);
    (update all the records where there id is in the sub-query that meet the WHERE Clause)
    AND
    UPDATE service_t SET status = 10100
    WHERE poid_type='/service/telephony'
    AND login >= min_login AND login <= max_login);
    (update all the records that meet the WHERE Clause)
    This should equate to the same record set, in which case the second update would be quicker without the sub-query.

  • Performance between SQL Statement and Dynamic SQL

    Select emp_id
    into id_val
    from emp
    where emp_id = 100
    EXECUTE IMMEDIATE
    'Select '|| t_emp_id ||
    'from emp '
    'where emp_id = 100'
    into id_valWill there be more impact in performance while using Dynamic SQL?

    CP wrote:
    Will there be more impact in performance while using Dynamic SQL?All SQLs are parsed and executed as SQL cursors.
    The 2 SQLs (dynamic and static) results in the exact same SQL cursor. So both methods will use an identical cursor. There are therefore no performance differences ito of how fast that SQL cursor will be.
    If an identical SQL cursor is not found (a soft parse), the SQL engine needs to compile the SQL source code supplied, into a SQL cursor (a hard parse).
    Hard parsing burns a lot of CPU cycles. Soft parsing burns less CPU cycles and is therefore better. However, no parsing at all is the best.
    To explain: if the code creates a cursor (e.g. INSERT INTO tab VALUES( :1, :2, :3 ) for inserting data), it can do it as follows:
    while More Data Found loop
      parse INSERT cursor
      bind variables to INSERT cursor
      execute INSERT cursor
      close INSERT cursor
    end loopIf that INSERT cursor does not yet exists, it will be hard parsed and a cursor created. Each subsequent loop iteration will result in a soft parse.
    However, the code will be far more optimal as follows:
    parse INSERT cursor
    while More Data Found loop
      bind variables to INSERT cursor
      execute INSERT cursor
    end loop
    close INSERT cursorWith this approach the cursor is parsed (hard or soft), once only. The cursor handle is then used again and again. And when the application is done inserting data, the cursor handle is released.
    With dynamic SQL in PL/SQL, you cannot really follow the optimal approach - unless you use DBMS_SQL (a complex cursor interface). With static SQL, the PL/SQL's optimiser can kick in and it can optimise its access to the cursors your code create and minimise parsing all together.
    This is however not the only consideration when using dynamic SQL. Dynamic SQL makes coding a lot more complex. The SQL code can now only be checked at execution time and not at development time. There is the issue of creating shareable SQL cursors using bind variables. There is the risk of SQL injection. Etc.
    So dynamic SQL is seldom a good idea. And IMO, the vast majority of people that post problems here relating to dynamic SQL, are using dynamic SQL unnecessary. For no justified and logical reasons. Creating unstable code, insecure code and non-performing code.

  • Perfomance review Cursor and dynamic SQL

    Hi every one ,
    I searcher over internet and oracle forums for what is the best for my case.
    I tried to rebuild indexes . I had two methods , Both working fine but I am looking for what is better from performance point of view
    1- using Cursor like in the below link .
    http://www.think-forward.com/sql/rebuildunusable.htm
    2- Using Dynamic SQL , which generated script file then run it.
    spool rebuildall.sql
    select ' alter index '|| owner||'.'||index_name ||' rebuild online; '
    from dba_indexes where status='UNUSABLE';
    spool off;
    @rebuildall.sql
    Thanks in advance . Your help is appreciated.

    Hi ,
    Thanks for your input . We had some customer which they have a lot of row chaining and migration , I need to increase PCTFREE
    with move command . As result of this command indexes becomes unusable as you know . So there are monthly tables become chained with wrong definitions in PCTFREE and INTRSAN.
    I used the above script as help my time and solve problem faster ,It is only when I need it ,So it is not scheduled or something like that .
    I'm looking for anything will help and simplify the work .

  • ODBC, bulk inserts and dynamic SQL

    I am writing an application running on Windows NT 4 and using the oracle ODBC driver (8.01.05.00, that inserts many rows at a time (10000+) into an oracle 8i database.
    At present, I am using a stored procedure to insert each row into the database. The stored procedure uses dynamic SQL because I can only determine the table and field names at run time.
    Due to the large number of records, it tends to take a while to perform all the inserts. I have tried a number of solutions such as using batches of SQL statements (e.g. "INSERT...;INSERT...;INSERT..."), but the oracle ODBC driver only seems act on the first statement in the batch.
    I have also considered using the FOR ALL statement and SQL*Loader utility.
    My problem with FOR ALL is that I'm not sure it works on dynamic SQL statements and even if it did, how do I pass an array of statements to the stored procedure.
    I ruled out SQL* Loader because I could not find a way to invoke it it from an ODBC statement. Secondly, it requires the spawining of a new process.
    What I am really after is something similar the the SQL Server (forgive me!) BULK INSERT statement where you can simply create an input file with all the records you want to insert, and pass it along in an ODBC statement such as "BULK INSERT <filename>".
    Any ideas??
    null

    Hi,
    I faced this same situation years ago (Oracle 7.2!) and had the following alternatives.
    1) Use a 3rd party tool such as Sagent or CA Info pump (very pricey $$$)
    2) Use VisualC++ and OCI to hook into the array insert routines (there are examples of these in the Oracle Home).
    3) Use SQL*Loader (the best performance, but no real control of what's happening).
    I ended up using (2) and used the Rouge Wave dbtools.h++ library to speed up the development.
    These days, I would also suggest you take a look at Perl on NT (www.activestate.com) and the DBlib modules at www.perl.org. I believe they will also do bulk loading.
    Your problem is that your program is using Oracle ODBC, when you should be using Oracle OCI for best performance.
    null

  • Ref cursors and dynamic sql..

    I want to be able to use a fuction that will dynamically create a SQL statement and then open a cursor based on that SQL statement and return a ref to that cursor. To achieve that, I am trying to build the sql statement in a varchar2 variable and using that variable to open the ref cursor as in,
    open l_stmt for refcurType;
    where refcurType is a strong ref cursor. I am unable to do so because I get an error indication that I can not use strong ref cursor type. But, if I can not use a strong ref cursor, I will not be able to use it to build the report based on the ref cursor because Reports 9i requires strong ref cursors to be used. Does that mean I can not use dynamic sql with Reports 9i ref cursors? Else, how I can do that? Any documentation available?

    Philipp,
    Thank you for your reply. My requirement is that, sometimes I need to construct a whole query based on some input, and sometimes not. But the output record set would be same and the layout would be more or less same. I thought ref cursor would be ideal. Ofcourse, I could do this without dynamic SQL by writing the SQL multiple times if needed. But, I think dynamic SQL is a proper candidate for this case. Your suggestion to use lexical variable is indeed a good alternative. In effect, if needed, I could generate an entire SQL statement and place in some place holder (like &stmt) and use it as a static SQL query in my data model. In that case, why would one ever need ref cursor in reports? Is one more efficient over the other? My guess is, in the lexical variable case, part of the processing (like parsing) is done on the app server while in a function based ref cursor, the entire process takes place in the DB server and there is probably a better chance for re-use(?)
    Thanks,
    Murali.

  • For loops and dynamic sql string syntax

    Hi
    is there a why to loop through a dynamic sql string
    normally you would have
    FOR cur IN (select * from emp) LOOP
    but I have a dynamic sql string called l_sql
    I have tried the following
    FOR cur IN l_sql LOOP
    but I get
    PLS-00456: item 'L_SQL' is not a cursorCompilation failed
    Any ideas?

    You will need to use ref cursors and the OPEN v_rc FOR '<your sql string'> and then loop through it as you would with any other OPEN, LOOP, EXIT WHEN, END LOOP syntax

  • XSQL Servlet and Dynamic SQL

    Does the XSQL servlet support dynamic SQL? Take a stock screening page as an example. In this example you want to dynamically build the where clause based on user input. Thus if a Minimum PE Ratio of 3 was entered, the where clause of "where PE_Ratio >= 3" would be appended to the query. In this case there may be up to 20 different parameters or more to be mapped dynamically, so it wouldn't be feasible to nest all of the different combinations.

    XSQL Supports lexical substitution parameters
    so any and every part of any query can be parameterized.
    The extreme case is:
    <query> {@sql} </query>
    where the entire query is passed in
    in a parameter (named "sql").
    But any combination of parameters
    and substitutions is legal and can
    be used to do what you want.
    Since the variables are not BIND
    variabled, but instead lexical
    substitution variables, you can
    do things like:
    <query>
    select {@collist}
    from {@table}
    where {@where}
    order by {@orderby}
    </query>
    You can provide default parameter values
    using XML attributes on the <query>
    element which then can be overridden
    if a value is passed in in the request...
    <query collist="ename, sal"
    orderby="sal desc"
    where="1=1"
    from="dept">
    select {@collist}
    from {@table}
    where {@where}
    order by {@orderby}
    </query>
    And then a request to the page
    can pass in a orderby=decode(comm,null,1,0)
    or something to override the defaults.
    null

  • Ref cursor and dynamic sql

    Hi..
    I'm using a ref cursor query to fetch data for a report and works just fine. However i need to use dynamic sql in the query because the columns used in the where condition and for some calculations may change dynamically according to user input from the form that launches the report..
    Ideally the query should look like this:
    select
    a,b,c
    from table
    where :x = something
    and :y = something
    and (abs(:x/:y........)
    The user should be able to switch between :x and :y
    Is there a way to embed dynamic sql in a ref cursor query in Reports 6i?
    Reports 6i
    Forms 6i
    Windows 2000 PRO

    Hello Nicola,
    You can parameterize your ref cursor by putting the query's select statement in a procedure/function (defined in your report, or in the database), and populating it based on arguments accepted by the procedure.
    For example, the following procedure accepts a strongly typed ref cursor and populates it with emp table data based on the value of the 'mydept' input parameter:
    Procedure emp_refcursor(emp_data IN OUT emp_rc, mydept number) as
    Begin
    -- Open emp_data for select all columns from emp where deptno = mydept;
    Open emp_data for select * from emp where deptno = mydept;
    End;
    This procedure/function can then be called from the ref cursor query program unit defined in your report's data model, to return the filled ref cursor to Reports.
    Thanks,
    The Oracle Reports Team.

  • DDL statements and dynamic  sql  in stored procedure

    I created a stored procedure to create and drop tables, using dynamic sql.
    When I try to do the inserts using dynamic sql, i.e
    v_string := 'INSERT statement';
    EXECUTE IMMEDIATE v_string;
    I get the following error message:
    ERROR at line 1:
    ORA-00942: table or view does not exist
    ORA-06512: at line 63
    Line 63 happens to be the line that the EXECUTE IMMEDIATE v_string; statement is in.
    I am able to describe the table that the inserts are being made into, so I know that the table exists.
    Any idea why I'm getting this error message would be appreciated.

    Yes I do and I have been able to create other tables using dynamic sql.
    The table that I am having problems with SELECTs data from another table to get its column values; within the SELECT statement, the CAST function is used:
    ie. CAST(CASE SUBSTR(CAST(E_MOD AS VARCHAR(7)),2,3)
    WHEN 'AAA' THEN 'A55'
    ELSE ............
    I get the following error message:
    ERROR at line 18: (this line starts the CAST statement)
    ORA-06550: line 18, column 13:
    PLS-00103: Encountered the symbol "AAA" when expecting one of the following:
    . ( * @ % & = - + ; < / > at in is mod not rem return
    returning <an exponent (**)> <> or != or ~= >= <= <> and or
    like between into using || bulk
    When I remove the quotes or add another single quote, the same error cascades to 'A55'.
    After doing the same for the next error, I get the error message below:
    ERROR at line 1: (this line has the EXECUTE IMMEDIATE statement)
    ORA-00936: missing expression
    ORA-06512: at line 6
    Any idea what the problem could be?
    Also is there another way to have DDL statements as stored procedures other than using dynamic sql or the DBMS_SQL package?

  • Bulk inserts and dynamic SQL

    I am writing an application running on Windows NT 4 and using the oracle ODBC driver (8.01.05.00, that inserts many rows at a time (10000+) into an oracle 8i database.
    At present, I am using a stored procedure to insert each row into the database. The stored procedure uses dynamic SQL because I can only determine the table and field names at run time.
    Due to the large number of records, it tends to take a while to perform all the inserts. I have tried a number of solutions such as using batches of SQL statements (e.g. "INSERT...;INSERT...;INSERT..."), but the oracle ODBC driver only seems act on the first statement in the batch.
    I have also considered using the FOR ALL statement and SQL*Loader utility.
    My problem with FOR ALL is that I'm not sure it works on dynamic SQL statements and even if it did, how do I pass an array of statements to the stored procedure.
    I ruled out SQL* Loader because I could not find a way to invoke it it from an ODBC statement. Secondly, it requires the spawining of a new process.
    What I am really after is something similar the the SQL Server (forgive me!) BULK INSERT statement where you can simply create an input file with all the records you want to insert, and pass it along in an ODBC statement such as "BULK INSERT <filename>".
    Any ideas??
    null

    Hi,
    I faced this same situation years ago (Oracle 7.2!) and had the following alternatives.
    1) Use a 3rd party tool such as Sagent or CA Info pump (very pricey $$$)
    2) Use VisualC++ and OCI to hook into the array insert routines (there are examples of these in the Oracle Home).
    3) Use SQL*Loader (the best performance, but no real control of what's happening).
    I ended up using (2) and used the Rouge Wave dbtools.h++ library to speed up the development.
    These days, I would also suggest you take a look at Perl on NT (www.activestate.com) and the DBlib modules at www.perl.org. I believe they will also do bulk loading.
    Your problem is that your program is using Oracle ODBC, when you should be using Oracle OCI for best performance.
    null

Maybe you are looking for

  • Unable to create database error

    Hello all- I've been working on a project in Robohelp7/HTML for about a week. I come in today and try to open my project and receive the error "Unable to create database. Check that the directory is not read-only.". I've done the obvious of checking

  • Help with an iPod Touch in recovery mode?

    4th generation iPod touch... So the iPod was running perfectly fine. Today I tried to update the iPod software, but it didn't work. I went online to try to figure out why, and I found that I should try updating the iTunes software, so I did. This upd

  • 11g Human Task; problem with Auto-Generate Task Form

    Version: WebLogic Server 10.3.5.0 Fri Apr 1 20:20:06 PDT 2011 1398638 Using book: Getting Started with Oracle SOA 11g R1, A Hands-On Tutorial Had success through Chapt 7. Now working through 8, Creating Human Tasks -- almost everything checks out. De

  • Action script problem

    I have an .as file with this code within it so when the send_pb button is pushed then onSendMessage causes the message to be sent.....I'd like the enter key on the keyboard to do the same thing. I tried various ways to do it within the .as file but n

  • I bought photoshop elements for windows in January.  I now have a macBook air.  How do I transfer? I do not now have the windows computer.

    I want to ask Adobe a simple question - how do I do this? I just want to know how I transfer my Photoshop Elements from a windows platform to an apple mac platform. George