SQL logic help for pl/sql block

Hi All,
I need your suggestions and comments for the below issue:
I have two tables: table A and table B
Table A has two columns as id and counts:
Id Counts
99 10
999 13
9999 7
Table B has two columns as Id and order:
Id Order
99 1
999 2
9999 3
We need to update Order in Table B such that Id having highest count in table A has Order as 1 in table B and it keep on increasing the order for other Ids based on decreasing counts in table A. This will be like a job which will run daily and look for counts in table A and update Order in table B according to it.
It seems to be simple but i am not getting it. Please help me out of this by writing some PL/SQL block.
I will really appreciate your all comments and responses.
Regards
Dev

Hi,
Keen2Learn wrote:
Hi All,
I am really greatful to all fo you for all your replies and comments. I change ORDER table to ORDERS. All you replies worked for me but there is some slight change in scenario which i need to discuss with you all.
E.g: Table A has 10 rows like below:
Id Counts Type
99 10 A
999 13 A
9999 7 C
99 4 B
999 2 C
88 2 A
77 1 C
777 3 B
777 5 A
888 2 CIf you'd like help, please post CREATE TABLE and INSERT statements for your sample data (including table b as it is before the UPDATE or MERGE).
I populate data in Orders column Table B based on id, by grouping sum of counts for that id in table A.
Id 999 has highest sum(count) as 15, so it has orders as 1 in Table B and do same for descending counts for each Id.
Table B has 5 rows like below:
Id Orders
99 2
999 1
88 4
777 3
555 5
Assume Table B as static(no new record comes in it) but only its Orders changes for each Id based on counts for that Id in Table A. As you see, Table B has id 555 which is not in Table A, so we need to update its orders to the highest number by taking its Count as 0(zero). Sorry, it's unclear what you want to do.
Post what you'd like table b to look like after the UPDATE or MERGE.
Right now i am doing it like this:
declare
     cursor c1 is
     select Id, SUM (COUNT), RANK () OVER (ORDER BY SUM (COUNT)) rnk
     from TableA      AND Id IN (SELECT Id FROM TableB)
GROUP BY Id
ORDER BY rnk DESC;
i NUMBER := 1;
begin
for curr in c1
loop
     update TableB      
set orders = i
     where id = curr.id;
     i := i + 1;
end loop;
end;I'm not sure what you're trying to do, but I'll bet you don't need PL/SQL to do it. Use a single UPDATE or MERGE statement (inside PL/SQL if necessary).
But it is not updating orders for Id 555 in TableB.There is no row for id=555 in table b, and, according to your requirements, there never will be, because "Table B as static(no new record comes in it)". It's behaving exactly as you said you wanted it to. What's the problem?
Please provide your suggesstions on what needs to be done to take care of this scenario. I will really appreciate your all suggesstions and comments. Please let me know if need some more explanation.Whenever you have a problem, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and the results you want from that data.
In the case of a DML operation (such as UPDATE) the sample data should show what the tables are like before the DML, and the results will be the contents of the changed table(s) after the DML.
Explain, using specific examples, how you get those results from that data.
Always say what version of Oracle you're using.

Similar Messages

  • Logical Reads for a SQL ID

    Dear Experts,
    Any idea how we can find out Logical reads for a SQL ID over a 24 hour period? AWR shows physical reads info.. any data dictionary view that captures logical I/O?
    Thanks

    Figured it out.. This is it:
    col Time_Taken for 999999999999
    col log_reads for 9999999999999
    select sql_id, sum(disk_reads_delta) as phy_reads, sum(BUFFER_GETS_DELTA) as log_reads, sum(ELAPSED_TIME_DELTA/1000000) as Time_Taken
    from dba_maint.DB_HIST_SQLSTATS
    where PARSING_SCHEMA_NAME='USERNAME' and BEGIN_INTERVAL_TIME>='03-JAN-13' and sql_id in ('abcdefghijkl')
    group by sql_id order by  phy_reads, log_reads, time_taken desc;

  • Help for pl/sql block

    need help on this to performance better.
    DECLARE
         FILE_READ UTL_FILE.FILE_TYPE;
         LOCATION VARCHAR2(128):='D:\PLSQL';
         FILENAME VARCHAR2(128):='TEST.txt';
         OPEN_MODE VARCHAR2(128):='r';
         V_LINE VARCHAR2(128);
         V_ORDERCODE CHAR(15);
         V_REST     CHAR(100);     
         V_OWNERCODE     CHAR(5);
         CURSOR C_ORD IS
         SELECT ORD.ORDERID,ORD.OWNERID
         FROM ORDERS ORD,OWNERS OWN
         WHERE ORD.ORDERCODE=V_ORDERCODE
         AND ORD.OWNERID=OWN.OWNERID
         AND OWN.OWNERCODE=V_OWNERCODE
         AND ORD.STATUS=10
         ORDER BY ORD.SEQ DESC;
         R_ORD          C_ORD%ROWTYPE;     
    BEGIN
         FILE_READ:=UTL_FILE.FOPEN(LOCATION,FILENAME,OPEN_MODE);
         LOOP
              BEGIN
                   UTL_FILE.GET_LINE(FILE_READ,V_LINE);
                   EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                             EXIT;
              END;
              V_OWNERCODE:=RTRIM(SUBSTR(V_LINE,0,5));
              V_ORDERCODE:=SUBSTR(V_LINE,7,15);
              V_REST:=SUBSTR(V_LINE,23,LENGTH(RTRIM(LTRIM(V_LINE))));
              OPEN C_ORD;
              FETCH C_ORD INTO R_ORD;
              IF C_ORD%FOUND THEN
                   UPDATE ORDERS SET UNDEF10=RTRIM(V_REST) WHERE ORDERCODE=V_ORDERCODE AND OWNERID=R_ORD.OWNERID;
              END IF;
              CLOSE C_ORD;
         END LOOP;
         UTL_FILE.FCLOSE(FILE_READ);
    EXCEPTION
         WHEN UTL_FILE.INVALID_MODE THEN
              RAISE_APPLICATION_ERROR(-20001,'INVALID_MODE');
         WHEN UTL_FILE.READ_ERROR THEN
              RAISE_APPLICATION_ERROR(-20002,'READ_ERROR');
         WHEN UTL_FILE.INVALID_PATH THEN
              RAISE_APPLICATION_ERROR(-20003,'INVALID_PATH');
         WHEN UTL_FILE.INVALID_FILEHANDLE THEN
              RAISE_APPLICATION_ERROR(-20004,'INVALID_FILEHANDLE');
         WHEN UTL_FILE.INVALID_OPERATION THEN
              RAISE_APPLICATION_ERROR(-20005,'INVALID_OPERATION');
         WHEN UTL_FILE.WRITE_ERROR THEN
              RAISE_APPLICATION_ERROR(-20006,'WRITE_ERROR');
         WHEN UTL_FILE.INTERNAL_ERROR THEN
              RAISE_APPLICATION_ERROR(-20007,'INTERNAL_ERROR');
         WHEN OTHERS THEN
              RAISE_APPLICATION_ERROR(-20008,SQLERRM);
    END;

    My obersvations for poor performance (although you have not defined what is "poor")
    1. Why ORDER BY in cursor ?
    2. Why CURSOR itself ?
    It seems to me that all you are doing is checking whether the SQL (in cursor) returns any data. If yes, yo are updating ORDERS table. You should be able to eliminate cursor entirely. That will save all processing on cursor.
    If you can explain (in english) what you are trying to achieve, I may be able to provide better solution.

  • Help for Pl/SQL Logic & Syntax used

    Hi, in Ivan Bayross' book, following example is given illustrating use of triggers.
    Create trigger audit_trail
    After update or delete on customer
    for each row
    DECLARE
    oper VARCHAR(20);
    BEGIN
    If updating then
    oper :='UPDATE';
    End if;
    If deleting then
    oper :='DELETE';
    End if;
    Insert into audit_cust
    Values(*:OLD.CUST_NO* , *:OLD.FNAME* );
    END;
    Questions :*
    1. Why : symbol is used in insert query above? Viz. :OLD.CUST_NO
    what does it indicate ?? ALso, what does . ( dot operator) indicates?
    OLD is not table name.
    2. In the program above what does this line mean??
    If deleting then
    oper :='DELETE';
    End if;
    We are just assigning value 'DELETE' to oper variable ?? or something else??

    Hi,
    So, still struggling on Ivan's book, eh ;-) ?
    1. :OLD and :NEW means you can refer to the old and new column values.
    They are only usable in triggers.
    So, if you're updating column X from 1 to 2, the value of :OLD.X = 1 and :NEW.X = 2 in your trigger only.
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/triggers.htm#CNCPT118
    http://www.oracle.com/pls/db102/search?word=TRIGGER&partno=
    We are just assigning value 'DELETE' to oper variable ?? or something else??I guess the autor meant do do this:
    Create trigger audit_trail
    After update or delete on customer
    for each row
    DECLARE
    oper VARCHAR(20);
    BEGIN
    If updating then
    oper :='UPDATE';
    End if;
    If deleting then
    oper :='DELETE';
    End if;
    Insert into audit_cust
    Values( :OLD.CUST_NO, : OLD.FNAME,  oper );
    END;He probably forgot to insert the oper variable in his audit table,

  • SQL Join help for multiple values in single field.

    Hello All,
    I need a help, I have two tables T1 and T2
    Content of T2 will be like
    T2. ID | T2.USERNAME
    ID1 | John
    ID2 | Peter
    ID3 | Mark
    Content of T1 is like
    T1.ID
    ID1 ID2 ID3
    ID2
    ID1 ID3
    I need to join these two tables and replace the T1.ID values with T2.USERNAME, for eg. Row one of T1 should be changed as John Peter Mark.
    Note: ID1 ID2 ID3 is a single value.
    Thanks for your help.
    Sathish.

    At Volder: I have made a slight enhancement. It's the same thing but the other way around as last week's regular expression thread. Remember the "and then the bird flew away"? ;-)
    SQL> create table t1
      2  as
      3  select 'ID1 ID2 ID3' id from dual union all
      4  select 'ID2' from dual union all
      5  select 'ID1 ID3' from dual union all
      6  select 'ID11 ID2' from dual
      7  /
    Tabel is aangemaakt.
    SQL> create table t2
      2  as
      3  select 'ID1' id, 'John' username from dual union all
      4  select 'ID2', 'Peter' from dual union all
      5  select 'ID3', 'Mark' from dual union all
      6  select 'ID11', 'Volder' from dual
      7  /
    Tabel is aangemaakt.
    SQL> select * from t1
      2   model
      3    reference r on (select t2.*, rownum rn from t2)
      4     dimension by (rn)
      5     measures(id, username)
      6    main m
      7     dimension by (id)
      8     measures(cast(id as varchar(200)) str)
      9     rules iterate(100) until (r.id[iteration_number+1] is null)
    10      (str[any] = replace(str[CV()], r.id[iteration_number+1],r.username[iteration_number+1]))
    11  /
    ID          STR
    ID1 ID2 ID3 John Peter Mark
    ID2         Peter
    ID1 ID3     John Mark
    ID11 ID2    John1 Peter
    4 rijen zijn geselecteerd.
    SQL> select id
      2       , str
      3    from t1
      4   model
      5         reference r on (select id,username,rownum rn from t2)
      6           dimension by (rn)
      7           measures (id, username)
      8         main m
      9           dimension by (id)
    10           measures (cast(' ' || id || ' ' as varchar2(200)) str)
    11           rules iterate(1000) until (r.id[iteration_number+1] is null)
    12           ( str[any] = replace
    13             ( str[cv()]
    14             , ' ' || r.id[iteration_number+1] || ' '
    15             , ' ' || r.username[iteration_number+1] || ' '
    16             )
    17           )
    18  /
    ID          STR
    ID1 ID2 ID3  John Peter Mark
    ID2          Peter
    ID1 ID3      John Mark
    ID11 ID2     Volder Peter
    4 rijen zijn geselecteerd.At Sathish: just look at the queries we have to come up with to do such a simple thing. As said many times before, I would also encourage you to change the design instead of executing the queries presented by Volder and me.
    Regards,
    Rob.
    Message was edited by:
    Rob van Wijk
    Just noticed I missed a final TRIM function around "str", so please add this.

  • Need help for the sql statement !!!!!

    hi all,
    i need a sql statement for a query, how can i get the result from the rownum between 100 and 150?
    plz help

    use a scrollable statement:
    PreparedStatement stat = Connection.prepareStement("select * from blah", ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = stat.executeQuery();
    rs.absolute(100);
    while (rs.next()) {
    String something = rs.get(1);
    Look into the JDK API reference for ResultSet to get an expalantion of scrollable statements.

  • Help for pl/sql

    Hi all
    I am new to oracle.Can anybody suggest me the books,websites to practise procedure,cursor,triggers,function,packages.specially assignments on this

    http://www.oracle.com/pls/db112/portal.portal_db?selected=1&frame=#developer_essentials
    http://asktom.oracle.com
    http://www.sqlsnippets.com/en/home.html

  • SQL migration scripts for MS SQL and Oracle when leaving Pointbase

    We have created a project that has some data in pointbase that is Portal related
    and need to migrate that information to MS SQL. Has anyone written or know of
    migration scripts that would move the data? Thanks in advance.
    Sincerely,
    Eric Ballou

    Here is a progression of the steps I'm taking in picture:
    Start
    http://img136.imageshack.us/my.php?image=oracle1ry9.jpg
    http://img504.imageshack.us/my.php?image=oracle2xt5.jpg
    http://img401.imageshack.us/my.php?image=oracle3id0.jpg
    http://img185.imageshack.us/my.php?image=oracle4pp7.jpg
    http://img76.imageshack.us/my.php?image=oracle5vi1.jpg
    End
    http://img73.imageshack.us/my.php?image=oracle6jl5.jpg
    Message was edited by:
    Cybercat

  • Help asked for a sql request - thanks

    Hello,
    I'm not a sql Guru... Who can help for this sql request ?
    First I have this:
    SELECT ADDINFO_ID, INFO, LANGUAGE_FK, ENGLISH_NAME
    FROM V_ADDINFOS
    WHERE LANGUAGE_FK = 'EN' (which is very simple...-)
    But now complicated... I have to add this in the same request:
    select sum(val) as nbrInfo
    from(
    select count(*) val from eccgis where addinfo1_fk = ADDINFO_ID
    union all
    select count(*) val from eccgis where addinfo2_fk = ADDINFO_ID
    union all
    select count(*) val from eccgis where addinfo3_fk = ADDINFO_ID
    union all
    select count(*) val from thirdgis where addinfo1_fk = ADDINFO_ID
    union all
    select count(*) val from thirdgis where addinfo2_fk = ADDINFO_ID
    In other words, for each row of the first select, I need to know how much it is linked in the tables eccgis and thirdgis...
    Hope is is clear... -)
    Thank you very very much,
    Michel

    Hi, Michel,
    Almost anywhere that SQL allows an expression (such as a column name, literal or function call) it also allows a scalar sub-query, a SELECT statement based on any table (or tables) that returns one column and (at most) one row. Like other sub-queries, scalar sub-queries can be corellated to the main query.
    To get the grand total you want on each row of your output:
    SELECT ADDINFO_ID, INFO, LANGUAGE_FK, ENGLISH_NAME
    , (select count(*) from eccgis where addinfo1_fk = ADDINFO_ID)
    + (select count(*) from eccgis where addinfo2_fk = ADDINFO_ID)
    + (select count(*) from eccgis where addinfo3_fk = ADDINFO_ID)
    + (select count(*) from thirdgis where addinfo1_fk = ADDINFO_ID)
    + (select count(*) from thirdgis where addinfo2_fk = ADDINFO_ID)
    AS nrbInfo
    FROM V_ADDINFOS
    WHERE LANGUAGE_FK = 'EN';VERY IMPORTANT: Each sub-query must be in parentheses. You'll get a run-time error if any scalar sub-query returns more than one row. (Returning no rows is okay: the value will be NULL).
    By the way, this looks like a bad table design. If each row in eccgis or thirdgis can be associated with more than one foreign key, they should be kept in a separate table. That's the standard way to handle many-to-many relationships.

  • Not able to return value for pl/sql to shell

    Hi,
    I'm calling pl/sql script from my shell script. Have set a flag in the pl/sql. Trying to return the value of the flag back to the shell script, but it is not working. My shell is ksh
    Please help....
    SHELL code trysnir.sh file--->
    <code>
    #!/bin/ksh
    flaga=50
    echo $flaga
    flaga=`sqlplus -S user/pass@sid@/opt/local/sql/update.sql > LOGFILE`
    echo aftersql
    echo $flaga
    if [ $flaga -lt 50 ]; then
    error "Previous Load failed"
    exit 3
    fi
    echo complete
    </code>
    SQL CODE file for update.sql--->
    <code>
    variable flaga number
    declare
    sessin_id number;
    begin
    Select Load_Sessin('aaa','xx') into sessin_id from dual;
    if sessin_id is NULL then
    :flaga :=10;
    end if;
    dbms_output.put_line(flaga);
    end;
    exit :flaga
    </code>
    But this returns me --->
    +50+
    aftersql
    PL/SQL procedure successfully completed.
    tyrnir.sh[9]: procedure: unknown test operator
    complete
    Please advise.... I have been trying since past 3 hrs and tried all search and everything i could but in vain.
    Many Thanks....
    Edited by: nss280 on Aug 20, 2009 2:17 AM

    executing this way will return you the last output from the sqlplus command. I think suppressing message PL/SQL procedure successfully completed. and putting a DBMS_OUTPUT.PUT_LINE(vflag) (this you have done already) will give you the desired result. So in update.sql put some extra line as below:
    set feedback off
    set serveroutput on
    <your code goes here>
    Regards.

  • SQL Server2008 help needed

    Having trouble with SQLServer 2008 (not MySQL) and my database connection in Dreamweaver CS6.  My document type is set as .asp using VBScript.  I can list the table information  but cannot use the insert wizard to add new records.  I don't get any errors after creating the insert form, but no records get inserted.  I'm not a VBScript expert, but do I have to manually write some code to insert records?  How do I attach it to a button?

    Thanks for the quick reply.  I won't be back in the office for a few days, but I'll try to post it when I get back in.  It's pretty much the code generated from the Dreamweaver Insert Record wizard.  I see where the submit button is created and the value is set but the action on the form is set to MM_insert, so I don't see where the submit code is actually called.
    Date: Wed, 3 Oct 2012 12:06:14 -0600
    From: [email protected]
    To: [email protected]
    Subject: SQL Server2008 help needed
        Re: SQL Server2008 help needed
        created by bregent in Dreamweaver General - View the full discussion
    This post should be moved to the app dev forum.  Please post the code from your form and the insert script pages.
         Please note that the Adobe Forums do not accept email attachments. If you want to embed a screen image in your message please visit the thread in the forum to embed the image at http://forums.adobe.com/message/4746757#4746757
         Replies to this message go to everyone subscribed to this thread, not directly to the person who posted the message. To post a reply, either reply to this email or visit the message page: http://forums.adobe.com/message/4746757#4746757
         To unsubscribe from this thread, please visit the message page at http://forums.adobe.com/message/4746757#4746757. In the Actions box on the right, click the Stop Email Notifications link.
         Start a new discussion in Dreamweaver General by email or at Adobe Community
      For more information about maintaining your forum email notifications please go to http://forums.adobe.com/message/2936746#2936746.

  • Need help for SQL SELECT query to fetch XML records from Oracle tables having CLOB field

    Hello,
    I have a scenario wherein i need to fetch records from several oracle tables having CLOB fields(which is holding XML) and then merge them logically to form a hierarchy XML. All these tables are related with PK-FK relationship. This XML hierarchy is having 'OP' as top-most root node and ‘DE’ as it’s bottom-most node with One-To-Many relationship. Hence, Each OP can have multiple GM, Each GM can have multiple DM and so on.
    Table structures are mentioned below:
    OP:
    Name                             Null                    Type        
    OP_NBR                    NOT NULL      NUMBER(4)    (Primary Key)
    OP_DESC                                        VARCHAR2(50)
    OP_PAYLOD_XML                           CLOB       
    GM:
    Name                          Null                   Type        
    GM_NBR                  NOT NULL       NUMBER(4)    (Primary Key)
    GM_DESC                                       VARCHAR2(40)
    OP_NBR               NOT NULL          NUMBER(4)    (Foreign Key)
    GM_PAYLOD_XML                          CLOB   
    DM:
    Name                          Null                    Type        
    DM_NBR                  NOT NULL         NUMBER(4)    (Primary Key)
    DM_DESC                                         VARCHAR2(40)
    GM_NBR                  NOT NULL         NUMBER(4)    (Foreign Key)
    DM_PAYLOD_XML                            CLOB       
    DE:
    Name                          Null                    Type        
    DE_NBR                     NOT NULL           NUMBER(4)    (Primary Key)
    DE_DESC                   NOT NULL           VARCHAR2(40)
    DM_NBR                    NOT NULL           NUMBER(4)    (Foreign Key)
    DE_PAYLOD_XML                                CLOB    
    +++++++++++++++++++++++++++++++++++++++++++++++++++++
    SELECT
    j.op_nbr||'||'||j.op_desc||'||'||j.op_paylod_xml AS op_paylod_xml,
    i.gm_nbr||'||'||i.gm_desc||'||'||i.gm_paylod_xml AS gm_paylod_xml,
    h.dm_nbr||'||'||h.dm_desc||'||'||h.dm_paylod_xml AS dm_paylod_xml,
    g.de_nbr||'||'||g.de_desc||'||'||g.de_paylod_xml AS de_paylod_xml,
    FROM
    DE g, DM h, GM i, OP j
    WHERE
    h.dm_nbr = g.dm_nbr(+) and
    i.gm_nbr = h.gm_nbr(+) and
    j.op_nbr = i.op_nbr(+)
    +++++++++++++++++++++++++++++++++++++++++++++++++++++
    I am using above SQL select statement for fetching the XML records and this gives me all related xmls for each entity in a single record(OP, GM, DM. DE). Output of this SQL query is as below:
    Current O/P:
    <resultSet>
         <Record1>
              <OP_PAYLOD_XML1>
              <GM_PAYLOD_XML1>
              <DM_PAYLOD_XML1>
              <DE_PAYLOD_XML1>
         </Record1>
         <Record2>
              <OP_PAYLOD_XML2>
              <GM_PAYLOD_XML2>
              <DM_PAYLOD_XML2>
              <DE_PAYLOD_XML2>
         </Record2>
         <RecordN>
              <OP_PAYLOD_XMLN>
              <GM_PAYLOD_XMLN>
              <DM_PAYLOD_XMLN>
              <DE_PAYLOD_XMLN>
         </RecordN>
    </resultSet>
    Now i want to change my SQL query so that i get following output structure:
    <resultSet>
         <Record>
              <OP_PAYLOD_XML1>
              <GM_PAYLOD_XML1>
              <GM_PAYLOD_XML2> .......
              <GM_PAYLOD_XMLN>
              <DM_PAYLOD_XML1>
              <DM_PAYLOD_XML2> .......
              <DM_PAYLOD_XMLN>
              <DE_PAYLOD_XML1>
              <DE_PAYLOD_XML2> .......
              <DE_PAYLOD_XMLN>
         </Record>
         <Record>
              <OP_PAYLOD_XML2>
              <GM_PAYLOD_XML1'>
              <GM_PAYLOD_XML2'> .......
              <GM_PAYLOD_XMLN'>
              <DM_PAYLOD_XML1'>
              <DM_PAYLOD_XML2'> .......
              <DM_PAYLOD_XMLN'>
              <DE_PAYLOD_XML1'>
              <DE_PAYLOD_XML2'> .......
              <DE_PAYLOD_XMLN'>
         </Record>
    <resultSet>
    Appreciate your help in this regard!

    Hi,
    A few questions :
    How's your first query supposed to give you an XML output like you show ?
    Is there something you're not telling us?
    What's the content of, for example, <OP_PAYLOD_XML1> ?
    I don't think it's a good idea to embed the node level in the tag name, it would make much sense to expose that as an attribute.
    What's the db version BTW?

  • Help required in changing to str for dynamic sql

    Hi
    I am trying to make this to string for dynamic sql, this is a part of the sql which is giving problem with p_..as parameters from proc. Help me in this , iam also seeing dbms _output but stil unable to format it to required error free string.
    || ' AND ( po.abbreviationprojectopportid LIKE '
    || '%'
    || 'NVL'
    || '('
    || p_opp_code
    || ', ''NULL'')'
    || '%'
    || ' OR co.companyname LIKE '
    || '%'
    || 'NVL'
    || '('
    || p_client_name
    || ', '' NULL'')'
    || '%'
    || ' OR le.line_item_amount = NVL '
    || ' ('
    || p_booking_amt
    || ', -0.197) '
    || 'OR po.dealcurrency = NVL '
    || '('
    || p_currency
    || ',''NULL'')'
    || 'OR be.booking_entry_id LIKE '
    || '%'
    || 'NVL ('
    || p_entry_id
    || ',''NULL'')'
    || '%'
    || ' OR le.line_item_id LIKE '
    || '%'
    || 'NVL ('
    || p_line_item
    || ',''null'')'
    || '%'
    || ' OR be.ticket_num LIKE '
    || '%'
    || 'NVL ('
    || p_ticket_num
    || ',''NULL'')'
    || '%'
    || ' OR be.updatedby LIKE '
    || '%'
    || 'NVL ('
    || p_user_name
    || ',''NULL'')'
    || '%'
    || ' OR credittransaction.acct_code ='
    || 'NVL ('
    || p_gl_account
    || ','
    || '-0.197)'
    || 'OR debittransaction.acct_code ='
    || 'NVL ('
    || p_gl_account
    || ', '
    || '-0.197) '
    || 'OR credittransaction.profit_ctr_code ='
    || 'NVL ('
    || p_profit_center
    || ','
    || ' -0.197)'
    || 'OR debittransaction.profit_ctr_code ='
    || 'NVL ('
    || p_profit_center
    || ','
    || '-0.197)'
    || ' OR le.sap_posting = NVL ('
    || p_sap_posting
    || ',''$'')'
    || 'OR cmis.cmis_code = NVL ('
    || p_cmis_nominal
    || ','' -0.197)'
    || 'OR sa.sap_code = NVL ('
    || p_sap_booking_entity
    || ', -0.197)'
    || ' OR (be.booking_date BETWEEN '
    || v_booking_date_from
    || 'AND '
    || v_booking_date_to
    || ')'
    || ' )'
    || 'ORDER BY '
    || p_sort_by
    || ' '
    || p_order;

    some errors.. Try this...
    ' SELECT be.booking_date bookingdate, '
    || ' be.booking_entry_id entryid, le.line_item_id itemid,'
    || ' po.abbreviationprojectopportid opportunitycode,'
    || ' co.companyname clientname, '
    || ' le.line_item_amount bookingamount,'
    || ' be.ticket_num ticketnum, po.dealcurrency currency,'
    || ' cmis.cmis_code cmis_nominal,'
    || ' sa.sap_code sap_booking_entity,'
    || ' (SELECT full_name '
    || ' FROM iba_employee '
    || ' WHERE TO_CHAR (employeeid) = be.updatedby) updatedby,'
    || ' be.updateddate updateddate, '
    || ' (SELECT le.line_item_amount * rate '
    || ' FROM iba_currencyconversion '
    || ' WHERE tocurrencycd = '
    || 'USD'
    || ' AND currencycd = po.dealcurrency '
    || ' AND conversiondate = be.booking_date) amountusd,'
    || 'debittransaction.acct_code debitglaccount,'
    || ' credittransaction.acct_code creditglaccount,'
    || ' debittransaction.profit_ctr_code debitprofitcenter,'
    || ' credittransaction.profit_ctr_code creditprofitcenter,'
    || ' debittransaction.amt debitamount,'
    || ' credittransaction.amt creditamount'
    || ' FROM rb_booking_entry be, '
    || ' rb_line_item le, '
    || ' rb_booking_period bp,'
    || ' rb_cmis_gl_account cmisgl,'
    || ' rb_cmis_account cmis,'
    || ' iba_projectopportunity po,'
    || ' iba_company co,'
    || ' rb_sap_account sa,'
    || ' (SELECT acctr.line_item_id line_item,'
    || ' sapgl_acc.account_code acct_code,'
    || ' acctr.amount amt,'
    || ' sappr.profit_center_code profit_ctr_code'
    || ' FROM rb_account_transaction acctr,'
    || ' rb_sap_profit_center sappr,'
    || ' rb_sap_gl_account sapgl_acc'
    || ' WHERE acctr.profit_center_id = sappr.profit_center_id '
    || ' AND acctr.gl_account_id = sapgl_acc.gl_account_id '
    || ' AND acctr.transaction_type = ''D'') debittransaction,'
    || ' (SELECT acctr.line_item_id line_item,'
    || ' sapgl_acc.account_code acct_code,'
    || ' acctr.amount amt,'
    || ' sappr.profit_center_code profit_ctr_code '
    || ' FROM rb_account_transaction acctr, '
    || ' rb_sap_profit_center sappr, '
    || ' rb_sap_gl_account sapgl_acc '
    || ' WHERE acctr.profit_center_id =sappr.profit_center_id '
    || ' AND acctr.gl_account_id = sapgl_acc.gl_account_id '
    || ' AND acctr.transaction_type = ''C'') credittransaction '
    || ' WHERE po.projectopportunityid = be.projectopportunityid '
    || ' AND be.booking_entry_id = le.booking_entry_id '
    || ' AND po.companyid = co.companyid '
    || ' AND bp.booking_period_id = be.booking_period_id '
    || ' AND cmis.cmis_id = cmisgl.cmis_id '
    || ' AND le.sap_id = sa.sap_id '
    || ' AND le.cmis_id = cmis.cmis_id '
    || ' AND debittransaction.line_item(+) = le.line_item_id '
    || ' AND credittransaction.line_item(+) = le.line_item_id '
    || ' AND ( po.abbreviationprojectopportid LIKE ' || '''%' || NVL(p_opp_code,'NULL') || '%'''
    || ' OR le.line_item_id LIKE '
    || '''%'
    || NVL (
    || p_line_item
    || ,'null')
    || '%'''
    | ' OR le.line_item_amount = '
    ||NVL(|| p_booking_amt, -0.197)
    || ' OR po.dealcurrency ='
    || NVL(p_currency,'NULL')
    || ' OR be.booking_entry_id LIKE '
    || '''%'
    || NVL (p_entry_id,'NULL')
    || '%'''
    || ' OR be.ticket_num LIKE '
    || '''%'
    || NVL (p_ticket_num,'NULL')
    || '%'''
    || ' OR be.updatedby LIKE '
    || '''%'
    || NVL (p_user_name,'NULL')
    || '%'''
    || ' OR credittransaction.acct_code ='
    || NVL (p_gl_account,-0.197)
    || ' OR debittransaction.acct_code ='
    || NVL (p_gl_account,  -0.197)
    || ' OR credittransaction.profit_ctr_code ='
    || NVL (p_profit_center, -0.197)
    || ' OR debittransaction.profit_ctr_code ='
    || NVL (p_profit_center, -0.197)
    || '  OR le.sap_posting = '
    ||NVL (p_sap_posting,'$')
    || ' OR cmis.cmis_code = '
    ||NVL (p_cmis_nominal, -0.197)
    || ' OR sa.sap_code = '
    || NVL (p_sap_booking_entity, -0.197)
    || '  OR (be.booking_date BETWEEN to_date('''
    || v_booking_date_from
    || ''') AND  to_date('''
    || v_booking_date_to
    || ''')'
    || ' OR co.companyname LIKE '
    || '''%'
    || NVL(p_client_name,'NULL')
    || '%'''
    || ' )'
    || 'ORDER BY  ' || p_sort_by || ',' || p_order;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Complex SQL help for a

    I do not know if this is the right place for thius type of post. If it is not please advise where the right place is.
    I need help generating a report, hopefully with SQL in 8.1.7
    SQL Statement which produced the data below the query :
    SELECT CHANGE.change_number, CHANGE.route_date as DATE_TO_CCB, nodetable.description AS Approver_required, (TRIM(BOTH ',' FROM CHANGE.PRODUCT_LINES)) AS PRODUCT_LINES /*, PROPERTYTABLE.VALUE as PRODUCT_LINES */
    FROM CHANGE, signoff, workflow_process, nodetable /*, PROPERTYTABLE */
    WHERE ( (CHANGE.ID = signoff.change_id)
    AND (CHANGE.process_id = signoff.process_id)
    AND ((nodetable.id = signoff.user_assigned) or (nodetable.id=signoff.user_signed))
    AND (CHANGE.process_id = workflow_process.ID)
    AND (CHANGE.ID = workflow_process.change_id)
    AND (CHANGE.workflow_id = workflow_process.workflow_id)
    AND (SIGNOFF.SIGNOFF_STATUS=0 )/* in (0, 2, 3)) */ /* 0=request needs attention, 2=request approved, 3=request rejected */
    AND (SIGNOFF.REQUIRED=5 or SIGNOFF.REQUIRED=1) /* 1=Approver 5= Ad Hoc Approver */
    AND (CHANGE.IN_REVIEW=1)
    AND (CHANGE.RELEASE_DATE IS NULL)
    AND (CHANGE.CLASS != '4928')
    /* AND (PROPERTYTABLE.PROPERTYID IN (SELECT TRIM(BOTH ',' FROM CHANGE.PRODUCT_LINES) FROM CHANGE)) */
    order by change.route_date desc
    **** Results **********
    CHANGE_NUMBER|DATE_TO_CCB|APPROVER_REQUIRED|PRODUCT_LINES
    C02190|11/14/2008 3:34:02 PM|Anurag Upadhyay|270354,270362|
    C02190|11/14/2008 3:34:02 PM|Dennis McGuire|270354,270362|
    C02190|11/14/2008 3:34:02 PM|Hamid Khazaei|270354,270362|
    C02190|11/14/2008 3:34:02 PM|Mandy York|270354,270362|
    C02193|11/14/2008 3:05:18 PM|Hamid Khazaei|274279,266339,266340,266341|
    C02193|11/14/2008 3:05:18 PM|Rob Brogle|274279,266339,266340,266341|
    C02193|11/14/2008 3:05:18 PM|Xavier Otazo|274279,266339,266340,266341|
    C02193|11/14/2008 3:05:18 PM|san|274279,266339,266340,266341|
    C02194|11/14/2008 2:51:34 PM|Diana Young|271503|
    C02194|11/14/2008 2:51:34 PM|Carl Krentz|271503|
    C02194|11/14/2008 2:51:34 PM|Dennis Yen|271503|
    C02194|11/14/2008 2:51:34 PM|Gordon Ries|271503|
    C02194|11/14/2008 2:51:34 PM|Sunil Khatana|271503|
    M00532|11/13/2008 1:34:42 PM|Dennis Yen|270356,270354,270360,274279,266339,266340,266341,276780,260784|
    M00532|11/13/2008 1:34:42 PM|Jin Hong|270356,270354,270360,274279,266339,266340,266341,276780,260784|
    M00532|11/13/2008 1:34:42 PM|Sunil Khatana|270356,270354,270360,274279,266339,266340,266341,276780,260784|
    Each value in the numeric comma delimited string has a corresponding ID for the actual test string value in another table as shown below.
    PROPERTYID|VALUE
    260775|product 1
    260776|Product 2
    260777|Product x
    260778|Product y
    260779|Internal
    260780|ORCA
    260781|Tiger
    260782|Orange product
    260783|Restricted
    260784|Product zz
    266259|Product YYY
    266260|Hercules
    266261|Tangerine
    *****Desired output****
    CHANGE_NUMBER|DATE_TO_CCB|APPROVER_REQUIRED|PRODUCT_LINES
    C02190|Nov/14/2008 03:34:02 PM|Anurag Upadhyay, Dennis McGuire, Hamid Khazaei, Mandy York|Product Y,Product 1
    C02193|Nov/14/2008 03:05:18 PM|Hamid Khazaei, Rob Brogle, Xavier Otazo, san|Hercules,Apple,Product 3,Product zz
    C02194|Nov/14/2008 02:51:34 PM|Diana Young, Carl Krentz, Dennis Yen, Gordon Ries, Sunil Khatana|Product 2
    M00532|Nov/13/2008 01:34:42 PM|Dennis Yen, Jin Hong, Sunil Khatana|Product 1,Product 4,product yy,product YYY,ORCA,Tiger,Orange product,Restricted

    Hi,
    Here's how you can do it in Oracle 8.1.
    To get the individual sub-strings from product_lines, join your current result set to this "counter table"
    (   SELECT  ROWNUM  AS n
        FROM    all_objects
        WHERE   ROWNUM <= 10 -- upper bound on number of items
    )  cntrIf you don't know the worst case of how many items might be in product_lines, it's a little more complicated:
    (   SELECT  ROWNUM  AS n
        FROM    all_objects
        WHERE   ROWNUM <= 1 +
                SELECT  MAX ( LENGTH (product_lines)
                            - LENGTH (REPLACE (product_lines, ','))
                FROM    table_name
    )  cntrJoin this to the existing result set like this
    WHERE   ...
    AND     INSTR ( product_lines || ','    -- one extra comma added
                  , 1
                  , n
                  ) > 0When you do the join, you will have
    one copy of all the rows with one item in producgt_lines,
    two copies of all the rows with two items in producgt_lines,
    three copies of all the rows with three items in producgt_lines,
    and so on.
    When a row has been copied, each copy will have a different value of cntr.n.
    To extract the n-th substring from product_lines:
    SELECT  ...
            SUBSTR ( product_lines
                   , INSTR ( ',' || product_lines,   ',',   1,   n)
                   , ( INSTR (product_lines || ',',   ',',   1,   n)
                     - INSTR (',' || product_lines,   ',',   1,   n)
                   )  AS product_lines_itemWhen you have derived this column, you can join to the table with the translations
    WHERE  TO_NUMBER (product_lines_item) = propertyidTo combine these rows into one row with a comma-delimited list, GROUP BY all the columns you want to select except the property_value ('produc 1', 'tangerine', etv.), and SELECT:
    LTRIM ( MAX (CASE WHEN n =  1 THEN ',' || property_value END) ||
            MAX (CASE WHEN n =  2 THEN ',' || property_value END) ||
            MAX (CASE WHEN n = 10 THEN ',' || property_value END)
          )I don't know a good way to re-combine the rows in Oracle 8 without assuming some limit on the number of items. I assumed there would never be more than 10 in the example above. You can say 20 or 100, I suppose, if you want to. If you guess too high, everything will still work: the query will just be slower.
    This is a just one example of why packing several values into a single column is a bad idea.

  • Newbie - need help with a SQL query for a bar chart

    Hi,
    I'm a new user on APEX with no real SQL knowledge and I'm trying to build a dashboard with charts into an existing APEX application. Based on another application, I have come up with the following SQL code:
    select null link
    , CATEGORY label
    , count (decode(PROJECT_STATUS,'1',PROJECT_ID))"Active"
    , count (decode(PROJECT_STATUS,'2',PROJECT_ID))"Complete"
    , count (decode(PROJECT_STATUS,'3',PROJECT_ID))"On Hold"
    , count (decode(PROJECT_STATUS,'4',PROJECT_ID))"Pipeline"
    , count (decode(PROJECT_STATUS,'5',PROJECT_ID))"Pending Review"
    from GRAPO_PROHEADTRK
    where (PROJECT_STATUS='1' or PROJECT_STATUS='2' or PROJECT_STATUS='3' or PROJECT_STATUS='4' or PROJECT_STATUS='5' or PROJECT_STATUS='6')
    group by CATEGORY
    Order by COUNT(PROJECT_ID) DESC
    The code from the other app was:
    select null link
    , FUNCTIONAL_AREA label
    , count (decode(PROJECT_STATUS,'Active',PROJECT_ID))"Active"
    , count (decode(PROJECT_STATUS,'Complete',PROJECT_ID))"Complete"
    , count (decode(PROJECT_STATUS,'On Hold',PROJECT_ID)) "On Hold"
    , count (decode(PROJECT_STATUS,'Recurring',PROJECT_ID))"Recurring"
    , count (decode(PROJECT_STATUS,'Pipeline',PROJECT_ID))"Pipeline"
    , count (decode(PROJECT_STATUS,'Not Approved',PROJECT_ID))"Not Approved"
    from PM_V2
    where LOB='S2S' and (FUNCTIONAL_AREA='Accounts Payable' or FUNCTIONAL_AREA='Expense' or FUNCTIONAL_AREA='Procurement' or FUNCTIONAL_AREA='Fixed Assets')
    group by FUNCTIONAL_AREA
    Order by COUNT(PROJECT_ID) DESC
    I'm getting a "Failed to parse SQL query!" error when I try to run validation.
    Is this enough info for some assistance? Any help would really be appreciated.
    Thanks,
    Rachel

    Hello,
    This is more of an SQL question, rather than specifically APEX-related. It's notable that you say: I'm a new user on APEX with no real SQL knowledgeWhich is fine (we all have to start somewhere, afterall) but it might be worth de-coupling the problem from APEX in the first instance. I'd also strongly recommend either taking a course, reading a book (e.g. http://books.google.co.uk/books?id=r5vbGgz7TFsC&printsec=frontcover&dq=Mastering+Oracle+SQL&hl=en#v=onepage&q=Mastering%20Oracle%20SQL&f=false) or looking for a basic SQL tutorial - it will save you a whole lot of heartache, I promise you. Search the oracle forums for the terms "Basic SQL Tutorial" and you should come up with a bunch of results.
    Given that you've copied your query template from another, I would suggest ensuring that the actual query works first of all. Try running it in either:
    * SQL Editor
    * SQL*Plus
    * an IDE like SQL Developer (available free from the OTN: http://www.oracle.com/technetwork/developer-tools/sql-developer/downloads/index.html ) or TOAD or similar.
    You may find there are syntax errors associated with the query - it's difficult to tell without looking at your data model.
    select null link
    , CATEGORY label
    , count (decode(PROJECT_STATUS,'1',PROJECT_ID))"Active"
    , count (decode(PROJECT_STATUS,'2',PROJECT_ID))"Complete"
    , count (decode(PROJECT_STATUS,'3',PROJECT_ID))"On Hold"
    , count (decode(PROJECT_STATUS,'4',PROJECT_ID))"Pipeline"
    , count (decode(PROJECT_STATUS,'5',PROJECT_ID))"Pending Review"
    from GRAPO_PROHEADTRK
    where (PROJECT_STATUS='1' or PROJECT_STATUS='2' or PROJECT_STATUS='3' or PROJECT_STATUS='4' or PROJECT_STATUS='5' or PROJECT_STATUS='6')
    group by CATEGORYNote that your "order by" clause references a field called "PROJECT_ID", which exists in the old query but you've changed other similar references to "PROJECT_STATUS" - is it possible you've just missed this one? The perils of copy-paste coding I'm afraid...

Maybe you are looking for

  • Bootcamp - Windows 8.1 - Mac Pro (Late 2013) -- ATI Driver Crash

    Hi All, I have a open case with Apple as well on this but i can not seem to locate any information on this issue on the web at all. Case: 601052633 Basically, we received a new Late 2013 Mac Pro, and out of the box proceeded to install bootcamp and w

  • Display image stored @ content managemenbt

    Hi, this is regarding to displaying image stored @ content management, using <html:img> tag in .jsp under a node i am uploading two images. (node having two upload options) in .jsp i am using <html:img> tag to display the images. i tried to display b

  • Creator and SDO

    Hi, What is the Creator's take on the Service Data Object(SDO) specification proposed by IBM and BEA in the JSR-235 Expert Group, and is now part of the JCP? Is this a technology that will be relavant and important to Creator developers, in the futur

  • Need help pulling up history on specific date

    i am trying to pull up history for a certain day in april..in the drop down menu april is not an option..today, last 7 days, last month or longer than 6 months..how can i pull up APRIL???

  • Can i use older chargers?

    Just want to know if the older chargers ( car charger and wall chargers ) is compatible with the touch. Thanks